【问题标题】:When should I use "ngProjectAs" attribute?我什么时候应该使用“ngProjectAs”属性?
【发布时间】:2021-11-23 17:07:28
【问题描述】:

我遇到了以下代码,其中ngProjectAs 属性在ng-container 中使用。它是做什么用的,解决了什么问题?

<mat-form-field [formGroup]="group">
  <input matInput [formControlName]="field.name">

  <ng-container *ngFor="let validation of field.validations;" ngProjectAs="mat-error">
    <mat-error *ngIf="group.get(field.name).hasError(validation.name)">{{validation.message}}</mat-error>
  </ng-container>
</mat-form-field>

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    当我想在某个选择器下投射ng-container 时,我发现ngProjectAs 很有用。

    Here你可以找到一篇关于它的短文。

    想象一下你有这个组件:

    @Component({
     selector: 'awesome-comp',
     template: `
      <ng-content select="[foo]"></ng-content>
     `
    })
    export class AwesomeComponent { }
    

    consumer.component.html

    如您所知,这就是您在 awesome-component 中投影内容的方式:

    <awesome-comp>
     <p>Hello there!</p> 
    </awesome-comp>
    

    但是当您想在同一个选择器下投射更多元素/组件时会发生什么?

    一种方法(不是真的推荐)是这样做:

    <awesome-comp>
     <div foo>
      <h1> <!-- ... --> </h1>
       <p> <!-- ... --> </p>
     </div> 
    </awesome-comp>
    

    如您所见,我们添加了一个冗余 div,以便能够投影多个元素。

    现在,ngProjectAs 是如何拯救这一天的:

    <awesome-comp>
     <ng-container ngProjectAs='[foo]'>
      <h1> <!-- ... --> </h1>
       <p> <!-- ... --> </p>
     </ng-container> 
    </awesome-comp>
    

    上面的 sn-p 不会添加任何多余的包装元素。

    【讨论】:

    • 还有这篇很棒的文章解释了*ngProjectAsmedium.com/ignite-ui/using-ng-content-ngprojectas-1664d7c1d3b的详细使用方法
    • 我不明白,因为只是使用&lt;ng-container foo&gt; 似乎有相同的输出。
    • @Steve 也许这取决于您使用的版本,如果我没记错的话,当时是 Angular 7-8。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多