【问题标题】:How to create an angular component that uses the contents of the component tag instead of an input如何创建一个使用组件标签内容而不是输入的角度组件
【发布时间】:2022-11-24 21:44:28
【问题描述】:

我想创建一个部分组件,它采用在开始和结束标记之间指定的 html 并添加一个标题。我想要这样做的主要原因是确保标题和内容的边距在整个网站上保持一致。我试图找到如何做到这一点,但我真的不知道如何提出问题以获得我需要的答案。 这是我正在寻找的组件 html 用法和结果的示例

用法:

<custom-component [headerText]='example text'>
    <button>example content</button>
</custom-component>

结果:

<custom-component
    <div>
        <h1>example text</h1>
        <button>example content</button>
    </div>
</custom-component>

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用类似于此示例的 @Input() 定义和 html 定义。 templateRef 类型的@Input() 允许您使用任何 html 代码或字符串文字,如您在 html 使用示例中所见

     @Input() title: TemplateRef<any>;
     @Input() titleOptions: TemplateRef<any>;
     @Input() actions: TemplateRef<any>;
    <mat-card >
        <mat-card-header >
            <mat-card-title>
                <ng-container *ngTemplateOutlet="title">
                </ng-container>
                <ng-container *ngTemplateOutlet="titleOptions">
                </ng-container>
            </mat-card-title>
        </mat-card-header>
    
        <mat-card-content >
            <ng-content> // Here puts html between your start and end tags component
            </ng-content>
        </mat-card-content>
    
        <mat-card-actions >
            <ng-container *ngTemplateOutlet="actions">
            </ng-container>
        </mat-card-actions>
    </mat-card>

    这是我如何使用它的一个例子。

    <ng-template #title>Custom Title here</ng-template>
     
    <ng-template #actions>
        <button color="action" mat-dialog-close mat-raised-button>Cancel</button>
        <button (click)="submit()"  class=" mr-3 ml-3" color="accent" form="form"
                mat-raised-button>
            Submit
        </button>
    </ng-template>
    
    <app-common-layout-dialog
            [actions]="actions"       
            [title]="title">
            
            <h1> Here put everything I need to use inside content section </h1>
            
    </app-common-layout-dialog>

    事实上,我也定义了 @Input() templateRef content ,但我删除了它以向您展示类似于您的请求的示例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 2017-05-19
      • 2020-06-30
      • 2018-12-01
      • 2017-06-13
      • 2019-09-27
      • 2019-12-28
      相关资源
      最近更新 更多