我什么时候应该使用“ngProjectAs"?属性? [英] When should I use "ngProjectAs" attribute?
问题描述
我遇到了以下代码,其中在 ng-container
中使用了 ngProjectAs
属性.它的用途是什么,解决什么问题?
<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-容器></mat-form-field>
我发现 ngProjectAs
在我想在某个选择器下投影 ng-container
时很有用.
在这里您可以找到关于它的简短文章.
想象一下你有这个组件:
@Component({选择器:'awesome-comp',模板:`<ng-content select="[foo]"></ng-content>`})导出类 AwesomeComponent { }
consumer.component.html
如您所知,这就是您在 awesome-component
中投影内容的方式:
<p>你好!</p></awesome-comp>
但是当您想在同一个选择器下投射更多元素/组件时会发生什么?
一种方法(不是真的推荐)是这样做:
<div foo><h1><!-- ... --><p><!-- ... --></p>
</awesome-comp>
如您所见,我们添加了一个冗余 div,以便能够投影多个元素.
现在,ngProjectAs
是如何拯救这一天的:
<ng-container ngProjectAs='[foo]'><h1><!-- ... --><p><!-- ... --></p></ng-容器></awesome-comp>
上面的代码片段不会添加任何多余的包装元素.
I've come across the following code where ngProjectAs
attribute is being used within ng-container
. what is it used for, and what problem is it addressing?
<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>
I find ngProjectAs
useful when I want to project an ng-container
under a certain selector.
Here you can find a short article about it.
Imagine you have this this component:
@Component({
selector: 'awesome-comp',
template: `
<ng-content select="[foo]"></ng-content>
`
})
export class AwesomeComponent { }
consumer.component.html
As you know, this is how you'd project content inside awesome-component
:
<awesome-comp>
<p>Hello there!</p>
</awesome-comp>
But what happens when you want to project more elements/components under the same selector?
One way(not really recommended) would be to do this:
<awesome-comp>
<div foo>
<h1> <!-- ... --> </h1>
<p> <!-- ... --> </p>
</div>
</awesome-comp>
As you can see, we're adding a redundant div in order to be able to project multiple elements.
Now, here is how ngProjectAs
saves the day:
<awesome-comp>
<ng-container ngProjectAs='[foo]'>
<h1> <!-- ... --> </h1>
<p> <!-- ... --> </p>
</ng-container>
</awesome-comp>
The above snippet won't add any redundant wrapper elements.
这篇关于我什么时候应该使用“ngProjectAs"?属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!