Select ComboBox two way binding in Angular 2

This is a note for me or anyone that needs it…

@Component({
providers: [CategoryService],
template: `
Add uma Category

Nome

Parent Category
[(ngModel)]=”category.parent_id”>

*ngFor=”let p of categories” [value]=”p.id”[attr.selected]=”p.id == category.parent_id”>
{{p.name}}

<button (click)=”add()”>Save</button>
<button (click)=”goBack()”>Back</button>
`
})

Basically this makes the item from a parent category select onclick and onchange and when rendered the selected attribute will equal the value of category.parent_id

attr accesses all the attributes of the Element and it has a property binding so the value of the resulting evaluation of p.id == category.parent_id will set it’s selected attribute value.

category: Category = {id:0, name: “”, description: “”, parent_id:0};

Also on the component I have

getCategories() : void {
this.categoryService.getCategories().then( res => this.categories = res);
}

To show all categories on the category select combobox

ngOnInit pulls the categories

ngOnInit() : void {
this.getCategories(); // <–
this.route.params
// (+) converts string ‘id’ to a number
.switchMap((params: Params) => this.categoryService.getCategory(+params[‘id’]))
.subscribe((category: Category) => this.category = category);
}

 

 

 

Advertisements

Sobre Fernando André
SysAdmin, Website and Application Developer

Deixe uma Resposta

Please log in using one of these methods to post your comment:

Logótipo da WordPress.com

Está a comentar usando a sua conta WordPress.com Terminar Sessão / Alterar )

Imagem do Twitter

Está a comentar usando a sua conta Twitter Terminar Sessão / Alterar )

Facebook photo

Está a comentar usando a sua conta Facebook Terminar Sessão / Alterar )

Google+ photo

Está a comentar usando a sua conta Google+ Terminar Sessão / Alterar )

Connecting to %s

%d bloggers like this: