Angular 2 - 根据输入值在模板中添加属性

时间:2016-10-15 09:53:21

标签: javascript angular

我希望只有在输入中设置时才添加required

<input-block 
    name="formName" 
    label="my label" 
    placeholder="test" 
    required
></input-block>

组件:

@Component({
    selector: 'input-block',
    inputs: ['name', 'label', 'placeholder', 'required'],
    template: `
        <label class="input-block">
            <span class="name">{{label}}</span>
            <input type="text" 
                name="{{name}}"
                placeholder="{{placeholder}}"
                <!-- no idea: {{required ? 'required : ''}} -->
            >
        </label>
    `
})

1 个答案:

答案 0 :(得分:4)

尝试类似的东西

<input type="text" 
        #myInput
        name="{{name}}"
        placeholder="{{placeholder}}"
        [attr.required]="myInput.value ? "required" : null">