Reputation: 1945
I need to be able to add buttons to the navbar programmatically. This HTML code should be added to the page (inside the <ion-navbar>
), by using a sort of template (in Angular 2) or by code (typescript).
<ion-buttons right (click)="doSth()">
<button ion-button outline icon-only color="primary" #hduiBtn>
<ion-icon name="home"></ion-icon>
</button>
</ion-buttons>
I found that ng-include
does not work in Angular 2, and while there are work-arounds, they are too messy to use in the situation I need it for.
I know Alerts can be created programmatically in Typescript, however, what about adding buttons? If not via standard classes, is it possible to do it by using @ViewChild()
? I tried different things (pipes, template includes via variables and more), but couldn't end up with anything working in a stable manner unfortunately.
Upvotes: 2
Views: 2735
Reputation: 8726
You can add html dynamically to your template from your typescript code. But you can not add angular code dynamically. Because angular complie once and it can not complie your dynamic code. So use html and pure javascript instead. Here is the example:
In html: <div id="parent"> </div>
In typescript:
let parent = <HTMLDivElement>document.getElementById('parent');
let button = document.createElement("button");
let text = document.createTextNode("Click me");
button.appendChild(text);
button.setAttribute('id','button1');
parent.appendChild(button);
let button1 = <HTMLButtonElement>document.getElementById('button1');
button1.addEventListener('click', (event) => {
//your code here
console.log("Button clicked");
})
Upvotes: 1
Reputation: 66
you can use ngFor. You fill your buttons list (object with button properties like icon , color) in your class and use ngFor in your template.
<ion-buttons right (click)="doSth()">
<button *ngFor='let button of buttons' ion-button outline icon-only color="{{color}}" #hduiBtn>
<ion-icon name="{{icon}}"></ion-icon>
</button>
</ion-buttons>
Upvotes: 2