如何以编程方式将离子按钮添加到Ionic导航栏? (Ionic 2,Angular 2)

时间:2017-04-13 17:37:18

标签: angular typescript ionic-framework ionic2

我需要能够以编程方式向导航栏添加按钮。应该使用一种模板(在Angular 2中)或通过代码(typescript)将此HTML代码添加到页面(<ion-navbar>内)。

<ion-buttons right (click)="doSth()">
    <button ion-button outline icon-only color="primary" #hduiBtn>
        <ion-icon name="home"></ion-icon>
    </button>
</ion-buttons>

我发现ng-include在Angular 2中不起作用,虽然有解决办法,但在我需要的情况下使用它们太麻烦了。

我知道可以在Typescript中以编程方式创建警报,但是,添加按钮呢?如果不是通过标准类,是否可以使用@ViewChild()来完成?我尝试了不同的东西(管道,模板包括通过变量等等),但不幸的是,它不能以稳定的方式工作。

2 个答案:

答案 0 :(得分:2)

你可以使用ngFor。您可以在类中填充按钮列表(具有图标,颜色等按钮属性的对象),并在模板中使用ngFor。

<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>

答案 1 :(得分:1)

您可以从打字稿代码动态地将html添加到模板中。但是你不能动态添加角度代码。因为角度编译一次,它无法编译您的动态代码。所以使用html和纯javascript代替。这是一个例子:
在html中:<div id="parent"> </div>
在打字稿中:

    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");
    })