【问题标题】:How to create a reusable button component with icons如何使用图标创建可重用的按钮组件
【发布时间】: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..)

  1. 我想从一个数组(或多个变量)中引用图标,就像我对 'btntxt' 所做的那样,或者能够在 other-page.component.html 文件中使用,但使用不起作用。
  2. 尝试设置 [attr.icon] - 为什么此模板无法访问 btnTxt(即使它设置为单个字符串,而不是数组)?
    1. 尝试在“other-page.component.html”中使用 {{ btnTxt }} 也会产生标识符未定义消息。

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

【问题讨论】:

  • 要传递输入,你应该像&lt;app-button [btnText]="yourVariable" [btnIconAdd]="yourIconVariable"&gt;&lt;/app-button&gt;那样做,这有帮助吗?

标签: angular templates


【解决方案1】:

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

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

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

并引用&lt;app-button&gt; 而不是@user184994 指出的按钮。 同样来自 user184994,我正确引用了我的属性和变量。

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

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

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

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

【讨论】:

    【解决方案2】:

    我在SB做了一个例子,也许你可以看看是不是你想做的,看最后一项(Generic Mat-button with Icon )

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

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2021-01-22
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2022-06-12
      • 1970-01-01
      相关资源
      最近更新 更多