【发布时间】:2018-08-27 14:25:47
【问题描述】:
我正在尝试创建一个可以在整个应用程序中重复使用的按钮模板/组件。还使用在整个应用程序中使用组件时设置的文本和图标。
我的 button.component.ts:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.scss']
})
export class ButtonComponent implements OnInit {
@Input() btnTxt = ['add item', 'remove item'];
@Input() btnIconAdd = ''; // <mat-icon>add_circle</mat-icon>;
constructor() {}
ngOnInit() {
}
}
button.component.html
<button mat-button
class="form-control" [attr.icon]="btnTxt">
<!-- <mat-icon>add_circle</mat-icon> --> // this works but isn't what I need.
{{btnIconAdd}} {{ btnTxt[0] }}
</button>
然后在另一个使用该按钮的 html 模板中(我们称之为“other-page.component.html”):
<app-button [attr.icon]="btnIconAdd"> // identifier not defined on btnIconAdd
<mat-icon>add_circle</mat-icon> // this does not work here
</app-button>
所以我这里有很多问题(比如不太了解 Angular..)
- 我想从一个数组(或多个变量)中引用图标,就像我对 'btntxt' 所做的那样,或者能够在 other-page.component.html 文件中使用,但使用不起作用。
- 尝试设置 [attr.icon] - 为什么此模板无法访问 btnTxt(即使它设置为单个字符串,而不是数组)?
- 尝试在“other-page.component.html”中使用 {{ btnTxt }} 也会产生标识符未定义消息。
非常感谢您的帮助,并随时告诉我“您做错了”。
【问题讨论】:
-
要传递输入,你应该像
<app-button [btnText]="yourVariable" [btnIconAdd]="yourIconVariable"></app-button>那样做,这有帮助吗?