2016-07-30 61 views
0

我正试图使用​​元数据来设置HTML输入属性。遵循属性指令指南(https://angular.io/docs/ts/latest/guide/attribute-directives.html),我想出了以下内容。reference peer(edit:parent)指令输入

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'" />
但使用material2它不会。
<md-input type="text" placeholder="Email" [(ngModel)]="model.username" name="username" [myModel]="model" [myProperty]="'username'"></md-input>
我看到物料输入组件有一个必需的@Input(https://github.com/angular/material2/blob/master/src/components/input/input.ts#L159),它传递给本地输入标签。我的问题是如何从我的指令中引用peer指令的输入?或者我正在以正确的方式进行?

注:用户名属性定义为

@required() 
public username: string; 

/** 
* 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不是同行,所以我用了以下内容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); 
     } 
    } 

}