【问题标题】:Reusing a component in another component but changing button name (Angular 4+)?在另一个组件中重用一个组件但更改按钮名称(Angular 4+)?
【发布时间】:2020-01-31 05:25:36
【问题描述】:

我有一个组件 (componentA) 在其 HTML 中使用另一个组件 (componentB)。 ComponentB 有一个按钮,其中的标题是别的东西,但我想更改 ComponentA 中按钮的名称。

ComponentA 使用 componentB 按钮导航到另一个页面,但 ComponentB 具有打开表单的按钮。导航工作正常,但我只想在按钮位于不同页面时更改按钮的名称。

组件A.html

<div>
    <component-b (click)="buttonEdit()"></component-b>
</div>

组件A.ts

public buttonEdit(): void {
    this.router.navigate(['/users']);
  }

组件B.html

<button (click)="openModal()">Add Users</button>

ComponentB.ts

 @Input() buttonEdit: () => void;

【问题讨论】:

    标签: html css angular


    【解决方案1】:

    试试这个

    组件 A.tmpl:

    <div>
        <component-b (click)="buttonEdit()" [buttonName]="buttonName()" [backgroundColor]="backgroundColor()"></component-b>
    </div>
    

    组件 A.ts:

    public backgroundColor(): string {
      ...
      return backgroundColor;
    }
    

    组件 B.tmpl:

    <div [ngStyle]="{'background-color': backgroundColor}"></<div>
    

    组件 B.ts:

    @Input() backgroundColor: string = 'green';
    

    【讨论】:

      【解决方案2】:

      你可以试试这个 组件 B.tmpl:

      <button (click)="openModal()">{{buttonName}}</button>
      

      组件 B.ts:

      @Input() buttonEdit: () => void;
      @Input() buttonName: string = 'Add Users';
      

      组件 A.ts:

      public buttonEdit(): void {
        this.router.navigate(['/users']);
      }
      public buttonName(): string {
        ...
        return buttonName;
      }
      

      组件 A.tmpl:

      <div>
          <component-b (click)="buttonEdit()" [buttonName]="buttonName()"></component-b>
      </div>
      

      【讨论】:

      • 如果我想在 componentA 中修复它的 CSS,有没有更简单的方法?
      • 你可以使用 ngStyle
      • &lt;div [ngStyle]="{'background-color':'green'}"&gt;&lt;/&lt;div&gt; 这是示例
      • 它不起作用...它仍然采用 componentA 背景颜色
      • 不,你应该从组件 A 收到 backgroundColor,比如 buttonName
      猜你喜欢
      • 1970-01-01
      • 2018-06-28
      • 2020-07-18
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      相关资源
      最近更新 更多