メタデータを使用してHTML入力属性を設定することにしています。アトリビュートディレクティブガイド(https://angular.io/docs/ts/latest/guide/attribute-directives.html)に続いて、私は次のことを考え出しました。リファレンスピア(編集:親)指示入力
import "reflect-metadata";
import { Directive, ElementRef, Input, OnInit} from '@angular/core';
@Directive({
selector: '[myModel]'
})
export class ModelDirectives implements OnInit {
private element: any;
@Input('myModel')
model: any;
@Input('myProperty')
propertyString: string;
constructor(elementRef: ElementRef) {
this.element = elementRef.nativeElement;
}
ngOnInit() {
if (this.model.hasOwnProperty(this.propertyString)) {
this.element.required = Reflect.getMetadata('required', this.model, this.propertyString);
//TODO other metadata
}
}
}
次の入力タグには、このディレクティブを使用する場合に必要な属性があります。
<input type="text" placeholder="Email" [(ngModel)]="model.username" name="username" [myModel]="model" [myProperty]="'username'" />
しかし、マテリアル2を使用してもそれはできません。
材料入力コンポーネントには、それがネイティブ入力タグに渡す必要な@Input(https://github.com/angular/material2/blob/master/src/components/input/input.ts#L159)があることがわかります。私の質問は、ピアディレクティブの指示を自分のディレクティブから参照する方法です。あるいは、私は正しい道を行くのだろうか?
注:ユーザ名プロパティは
/**
* Property decorator for form models.
* @param isRequired Whether property is required for html form, defaults to true.
*/
export function required(isRequired?: boolean): PropertyDecorator {
return Reflect.metadata('required', isRequired ? isRequired : true);
}