Angular - 如何绑定按钮以用于不同用途?

问题描述 投票:0回答:2

我是Angular和TypeScript的新手。

我必须做一个可以有文字或图标或文字+图标的按钮。

例:

按钮图标,文字component.html

<button>
  TEST BUTTON
</button>

app.component.html

<app-button-icon-text {here I have to choose beetwen TEXT or ICON}></app-button-icon-text>

按钮图标,文字component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-button-icon-text',
  templateUrl: './button-icon-text.component.html',
  styleUrls: ['./button-icon-text.component.css']
})
export class ButtonIconTextComponent implements OnInit {

{ADD SOME LOGIC}

  constructor() { }

  ngOnInit() {
  }

}
html angular typescript components frontend
2个回答
1
投票

使用@Input装饰器并在其上设置'TEXT''ICON'

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

app.component.html:

<app-button-icon-text type="TEXT"></app-button-icon-text>

按钮图标,文本component.ts:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-button-icon-text',
  templateUrl: './button-icon-text.component.html',
  styleUrls: ['./button-icon-text.component.css']
})
export class ButtonIconTextComponent implements OnInit {

  @Input()
  type // TEXT or ICON

  constructor() { }

  ngOnInit() {
  }

}

按钮图标,文本component.html:

<button *ngIf="type === 'TEXT'">
  TEST BUTTON
</button>
...

2
投票

这些是我的3个例子:

对于我安装的图标:npm i material-icons

然后我在style.css中导入了材料:@import'~sterial-icons / iconfont / material-icons.css';

app.component.html

//text button
<app-button-icon-text [text]="'test'"></app-button-icon-text>
  <br><br>

//iconbutton
  <app-button-icon-text [icon]="'face'"></app-button-icon-text>
  <br><br>

//icon + text button
  <app-button-icon-text [text]="'test'" [icon]="'face'"></app-button-icon-text>

按钮图标-text.component.html

<button>
  <span *ngIf="icon"  class="material-icons">{{icon}}</span>
  {{text}}
</button>

按钮图标-text.component.html

import {Component, Input, OnInit} from '@angular/core';

@Component({
  selector: 'app-button-icon-text',
  templateUrl: './button-icon-text.component.html',
  styleUrls: ['./button-icon-text.component.css']
})
export class ButtonIconTextComponent implements OnInit {

  @Input()
  text;

  @Input()
  icon;

  constructor() {
  }

  ngOnInit() {
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.