如何使用图标创建可重复使用的按钮组件

时间:2018-08-27 14:25:48

标签: angular templates

我正在尝试创建一个可以在整个应用程序中重复使用的按钮模板/组件。还使用在应用程序中使用组件时设置的文本和图标。

我的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。)

  1. 我想像使用“ btntxt”一样,引用数组(或多个var)中的图标,或者可以在other-page.component.html文件中的里面使用,而无法使用。
  2. 尝试设置[attr.icon]-为什么此模板无法访问btnTxt(即使将其设置为单个字符串而不是数组)?
    1. 尝试在“ other-page.component.html”中使用{{btnTxt}}也会产生未定义的标识符消息。

非常感谢您的帮助,并随时告诉我“您做错了”。

2 个答案:

答案 0 :(得分:0)

我在SB中举了一个例子,也许您可​​以看到它是否正在尝试做,请查看最后一项(带有Icon的通用Mat按钮)

https://stackblitz.com/edit/angular-rb5vmu

答案 1 :(得分:0)

解决方案是按照user184994所说的去做,但是带有图标的地方稍有不同。 回顾:尝试制作一个可以与其他文本,图标和方法调用一起使用的按钮元素:

我简化了button.ts文件,使其不再使用可能的值数组:

export class ButtonComponent implements OnInit {
  @Input() btnTxt: string;
  @Input() btnIcon: string;

并引用<app-button>而不是@ user184994指出的按钮。 同样从user184994,我正确引用了我的属性和变量。

在我的“ other-page.component.html”文件中(请注意双引号和单引号,这是为了避免在other-page.comnponent中设置属性值。 ts < / strong>,而是可以访问按钮组件ts文件中的值)。 “ add_circle”是图标名称:

  <app-button-with-icon [btnTxt]="'hello'" [btnIcon]="'add_circle'">
  </app-button-with-icon>

最后是我的button.component.html,如下所示。我遇到的一个问题是能够在使用按钮时指定一个图标,我无法将图标标记放置在另一页模板中,而不得不将标记放置在按钮组件模板中并引用一个空字符串变量,然后在使用按钮的模板中设置值(请参见上一代码段)。

<button mat-button class="form-control primary">
  <mat-icon>{{btnIcon}}</mat-icon>
  {{btnTxt}}
</button>