【问题标题】:How to pass-through directives from custom component to it's children?如何将指令从自定义组件传递给它的子组件?
【发布时间】:2019-01-09 23:36:36
【问题描述】:

我知道如何使用 @Input() 装饰器,但我要问的是如何传递未明确编程为输入的指令,尤其是自定义输入组件上的验证器

我的目标是构建一个输入组件,它接受很少的预设指令来提供标签、字段名称等,并且能够将所有剩余的指令传递给底层输入元素。

最好将验证器数组作为自定义输入的指令传递,并使用它将指令插入底层输入 + 从中构建验证消息,但在最坏的情况下,我可以混合使用这两种方法

有可能吗?

编辑:我不确定我应该提供什么样的伪代码,但我会尽力而为

<div>
  <ion-label>{{labelText}}</ion-label>
  <ion-input [type]="(inputType) ? inputType : 'text'" [name]="fieldName"></ion-input>
  <div *ngIf="field.errors && (field.dirty||field.touched)" class="error-contener">    
    <div class="error-message" *ngIf="field.errors?.required">Field is required</div>
  </div>
</div>



@Component({
  selector: 'custom-input',
  templateUrl: 'custom-input.html',
})

export class CustomInputComponent{

  @Input() fieldName: string;
  @Input() labelText: string;
  @Input() inputType: string;
  @Input() validatorsArray: any[];

  constructor(){}

}

这基本上是组件的完全简化版本,省略了导入,现在最好的解决方案是能够基于 validatorsArray&lt;ion-input&gt; 标签添加指令以及一些自定义代码翻译它(数组的其他部分用于构建下面的错误),但如果我能够将 &lt;custom-input&gt; 标记中未明确列为输入的每个指令传递到 &lt;ion-input&gt; 标记,我会很好

【问题讨论】:

  • 你能提供至少某种伪代码或文件结构吗?有几种方法可以做到这一点,所以我需要一个更具体的例子
  • @undefinedMayNotBeNull 我编辑了我的问题,我希望现在我想要实现的目标更容易理解(构建一个包含所有这些标记的表单是一个可怕的样板,在即将到来的未来我们甚至可能会根据来自服务器的数据制作这些表格)

标签: angular angular-components


【解决方案1】:

听起来你想实现 NgValueAccessor Have a look at this guide

这样您就可以将Angulars Form API 与您的自定义组件一起使用。 然后,您可以使用 Angular 和 HTML 表单验证。

理想情况下,您将拥有:

<form [formGroup]="form">
  <custom-input formControlName="user" type="text" required></custom-input>
  <custom-input formControlName="password" type="password" required></custom-input>
</form>

TS:

public form: FormGroup = new FormGroup({
    user: new FormControl(null, [Validators.required])
    password: new FormControl(null, [Validators.required, yourValidator])
})

如果您实现自定义验证器,还请确保使用 Angulars API。 Here is a guide for custom validation.

【讨论】:

  • 传递的指令将包括我自己的验证器,如果它有任何不同的话,我会好好阅读它,希望它能按我的预期工作,谢谢
  • 我在答案中添加了更多信息。这一切都是可能的,应该使用 API 来完成
猜你喜欢
  • 2018-06-14
  • 1970-01-01
  • 2020-04-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
  • 2021-10-30
  • 2021-12-28
相关资源
最近更新 更多