Angular 7 - 动态添加指令

5
<input  {{field.validatorDirective}} 
        class="form-control" 
        [ngClass]="{ 'border-danger': hasErrors }" 
        (keyup)="callback()" 
        [formControlName]="field.key" 
        [id]="field.key"
        [type]="field.type" 
        [placeholder]="field.placeholder" 
        [value]="field.value">
field包含了所需的所有内容,但我希望能动态地添加指令名称。
目前它作为string添加在field.validatorDirective中。
这会导致错误:

TextComponent.html:2 ERROR DOM Exception: Failed to execute 'setAttribute' on 'Element': '{{field.validatorDirective}}' is not a valid attribute name.

我的指令选择器是usernameValidator

尝试像这样使用 {{field?.validatorDirective}} 吗? - programoholic
不,你不能这样做。 - JB Nizet
我已经添加了指令名称 usernameValidator,它将作为 field.validatorDirective 传递。 - user9366125
这可能会有所帮助 --> https://dev59.com/SFgR5IYBdhLWcg3wd9G5#43752424 - Bunyamin Coskuner
1个回答

3

看起来你不能这样做。我尝试了 [attr.directiveSelector]="condition",但也无法使用。

如果你有兴趣,可以采用一种解决方法,即在两个输入框上都使用 *ngIf。像这样:

<input  directive1
    *ngIf="condition1"
        class="form-control" 
        [ngClass]="{ 'border-danger': hasErrors }" 
        (keyup)="callback()" 
        [formControlName]="field.key" 
        [id]="field.key"
        [type]="field.type" 
        [placeholder]="field.placeholder" 
        [value]="field.value">

<input directive2
    *ngIf="condition2"
    class="form-control" 
    [ngClass]="{ 'border-danger': hasErrors }" 
    (keyup)="callback()" 
    [formControlName]="field.key" 
    [id]="field.key"
    [type]="field.type" 
    [placeholder]="field.placeholder" 
    [value]="field.value">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接