Display boot warning with angular2

I want to display a Bootstrap warning when the user has saved the data.

my code is as follows:

html page:

<div class="alert alert-success" *ngIf="saveSuccess"> <strong>Success!</strong> </div> <form #f="ngForm" (submit)="saveUser(f.value)"> /////Some form fields <button class="form-control btn btn-primary" type="submit">save</button> </form> 

app.component.ts:

 export class UserProfileComponent{ saveSuccess: boolean; user: IUser; saveUser(user:IUser) { this.headers = new Headers(); this.headers.append('Content-Type', 'application/json'); this.editUserForm = user; this._http.post('api/user/'+this._current_user._id, JSON.stringify(this.editUserForm),{ headers: this.headers }).subscribe(function(data) { // if the update is successful then set the value to true // this is getting updated if (data){ this.saveSuccess = true; } else{ this.saveSuccess = false; } }); } 

}

I want to show a warning when a successful POST is executed.

I think that I am missing how to bind the saveSuccess variable to html so that a warning is displayed when saving is successful. (I'm new to Angular2)

+6
source share
2 answers

Last night I did not see this, probably too late. But your problem is not in the this context in the built-in function where you install saveSuccess .

I suggest you use lambdas or the "thick arrow function". Instead

 function(data) { ... } 

You doing

 (data) => { ... } 

This will save the this context. Just use it wherever you need the built-in function and you will have no more problems! :)


Your code with lambda function:

 export class UserProfileComponent{ saveSuccess: boolean; user: IUser; saveUser(user:IUser) { this.headers = new Headers(); this.headers.append('Content-Type', 'application/json'); this.editUserForm = user; this._http.post('api/user/'+this._current_user._id, JSON.stringify(this.editUserForm),{ headers: this.headers }) .map((data: Response) => data.json) // <-- also add this to convert the json to an object .subscribe((data) => { // <-- here use the lambda // if the update is successful then set the value to true // this is getting updated if (data){ this.saveSuccess = true; } else{ this.saveSuccess = false; } }); } } 
+4
source

Consider this dynamic alert component:

Angular2 Service that creates, displays, and manages an internal component? How to implement js alert ()?

eg: .

 this.alertCtmService.alertOK("Save changes???").subscribe(function (resp) { console.log("alertCtmService.alertOK.subscribe: resp=" + resp.ok); this.saveData(); }.bind(this) ); 

See demo here.

+1
source

All Articles