输入时没有表单标记的表单验证 - Angular 2

时间:2017-10-24 07:53:53

标签: forms angular tags

我有弹出组件,我想在输入元素上插入表单验证名称(必填字段和最小长度为3个字符)。 如果不在表单标签中设置完整代码,是否可以这样做?

<div class="scenario-div">
<label style="font-size: 1.4rem; font-weight: 400; margin-bottom: 10px;">{{context.header}}</label>
<div class="" style="width: 90%; margin-bottom: 10px; align-self: center;">
    <div style="display: flex; flex-direction: column; margin-bottom: 10px;">
        <label style="font-size: 1.2rem; font-weight: 500;">Name</label>
        <div style="display:flex; flex-direction:row;">
            <input type="text" [(ngModel)]="context.name" placeholder="enter Name" style="color: #569bd2; margin: 0px; width: 50%" minlength="3" required/>

            <select *ngIf="context.showOptionDropdown" class="custom-select-project" style="width:50%" #optionSelect (change)="context.option.value">
                <option disabled>Select type</option>
                <option value="option1">option1</option>
                <option value="option2">option2</option>
                <option value="option3">option3</option>
                <option value="option4">option4</option>
            </select>
        </div>
    </div>

    <div style="display: flex; flex-direction: column; margin-bottom: 10px;" *ngIf="!context.hideDescription">
        <label style="font-size: 1.2rem; font-weight: 400;">Description</label>
        <textarea rows="4" [(ngModel)]="context.description" cols="50" maxlength="250" placeholder="Enter text here" style="color: #569bd2; resize: none; font-weight: 400; font-size: 1.2rem;"></textarea>
    </div>
</div>
<div>   
    <button class="btn-main" (click)="confirm(context)" style="width: 15%;">Confirm</button>
</div>

2 个答案:

答案 0 :(得分:5)

&#39;验证&#39;基于ngModel

<input type="text" (keyup)='0' #title>
<span style="color:red" *ngIf="title.value.length > 10">
      10 max
</span>
<span style="color:red" *ngIf="!title.value">
      required
</span>

<button [disabled]="title.value.length > 10 || !title.value">OK</button>

DEMO

<小时/> &#39;验证&#39;基于本地模板变量:

shownotify()

DEMO

答案 1 :(得分:2)

您需要使用反应式表单API中的adb shell screencap -p | perl -pe 's/\x0D\x0A/\x0A/g' > screen.png ,该API可以与未包含在FormControl标记中的独立<input>一起使用。

<form>