2016-07-30 5 views
0

メタデータを使用して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); 
} 

答えて

0

は、だから私は私の[myModel]ディレクティブがangular2の依存性注入にmd-inputないピアに子と考えられることが分かった

@required() 
public username: string; 

として定義されます、私は以下を使用しましたhttps://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#find-parent

import "reflect-metadata"; 
import { Directive, ElementRef, Input, OnInit, Optional } from '@angular/core'; 
import { MdInput } from '@angular2-material/input'; 

@Directive({ 
    selector: '[tstModel]' 
}) 
export class ModelDirectives implements OnInit { 

    private inputElement: HTMLInputElement; 

    @Input('tstModel') 
    model: any; 

    @Input('tstProperty') 
    propertyString: string; 


    constructor(elementRef: ElementRef, @Optional() private mdInput: MdInput) { 
     this.inputElement = elementRef.nativeElement; 
    } 

    ngOnInit() { 
      this.mdInput.required = Reflect.getMetadata('required', this.model, this.propertyString); 
     } 
    } 

} 
関連する問題