reference peer(edit:parent)指令输入

时间:2016-07-30 02:25:19

标签: javascript html angular angular2-directives

我想要使用元数据来设置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它不会 <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),它传递给本机输入标签。我的问题是如何从我的指令中引用同伴指令的输入?或者我是以正确的方式前进的?

注意:username属性定义为

@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);
}

1 个答案:

答案 0 :(得分:0)

所以我发现我的[myModel]指令被认为是md-input的子节点而不是angular2依赖注入中的对等节点,所以我使用了以下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);
        }
    }

}