首页 文章

重新使用角度组件

提问于
浏览
0

我有一个名为 list 的组件,它有 fab-buttonicontooltip-text 它看起来像这样:

enter image description here

我想把它变成 generic component ,这样我就可以重新使用这个组件 . 所以我在另一个名为 SCHOOLCOLLEGE 的组件中重用 list 组件,如下所示:

enter image description here

我正在重新使用 list 组件,但我想根据它所在的组件更改 fab-button's 图标和 tooltip text(i,e add-school) .

手段

1)如果 SCHOOL 组件中存在 list 组件, fab-button icontooltip-text 应该不同 .

2)如果 list 组件中存在 list 组件, fab-button icontooltip-text 应该不同 .

如何根据 component 动态更改 iconstooltip-text ?我没有为 components reusability 找到任何资源 .

这是stackblitz DEMO .

3 回答

  • 0

    根据您当前的要求,您需要有3 @input 和1 @Output

    @Input()
      public tooltip;  //<-- pass tooltip text
    
      @Input()
      public buttonType; //<-- pass button style class
    
      @Input()
      public contacts;  //<-- pass contact from the college or school
    
      @Input()
      public add = new EventEmitter(); //<-- Emit Add event so that it can capture in the respective component College or School.
    

    工作演示在这里 - https://stackblitz.com/edit/angular-material2-issue-udhiaz

  • 2

    您应该使用 @Input .

    在列表组件TS文件中,添加输入属性:

    @Input()
     public tooltip;
    

    在模板中,使用此值而不是硬编码值

    <button mat-fab color="primary" id="add-button" [matTooltip]="tooltip"><i class="material-icons" >person_add</i></button>
    

    然后,您可以传入值,如下所示:

    <app-list tooltip="Add School"></app-list>
    

    Here is a Stackblitz demo

  • 0

    您可以将数据作为 @Input() 属性传递给 list 组件 - 如果它是 tooltip 您只需添加为字符串并将其绑定在 html 中 - 如果它是图标您可以直接发送图标

    @Input() tooltips;
    

    从父母那里传来 <app-list tooltips="Add School"></app-list>

    <button mat-fab color="primary" id="add-button" [matTooltip]="tooltips"><i class="material-icons" >person_add</i></button>
    

    现在您要传递图标的情况 - 您可以使用内容投影添加

    list.component.html

    <div>
        <mat-selection-list  #contact>
            <mat-list-option *ngFor="let contact of contacts">
                <a mat-list-item><span>{{ contact }}</span> </a>
            </mat-list-option>
          </mat-selection-list>
          <ng-content></ng-content>
      </div>
    

    加载组件时传递图标

    <app-list>
       <button mat-fab color="primary" id="add-button" matTooltip="Add School"><i 
         class="material-icons" >person_add</i></button>
    </app-list>
    

    通过这种方式,您甚至可以根据加载的组件更改图标甚至工具提示 - 如果您要根据 class 名称更改图标,则可以将类名作为另一个 @Input() 属性传递给子项

    希望这能帮到你 - 快乐编码:)

相关问题