2017-06-18 79 views
0

當文本輸入包含特定值時,我想顯示div。向ng鍵添加條件

對於我的模板,我有:

<input type="text" id="jobTitle" 
(click)="autoCompleteClick()" 
(keypress)="autoCompleteKeypress()" name="autocomplete" 
placeholder="Job Title" value="" > 

我的想法是按鍵將運行autoCompleteKeyPress功能看起來像這樣:

autoCompleteKeypress() { 
    if (this.jobTitle == 'bar' || this.jobTitle == 'Bar'){ 
     alert('BOO!'); 
    } 
} 

目前我只是用一個測試警惕讓它工作。

我的全成分爲:

import { Component } from '@angular/core'; 
import { Input } from '@angular/core'; 

@Component({ 
    selector: 'sign-up', 
    templateUrl: './sign-up.component.html', 
    styleUrls: ['../variables.less', './sign-up.component.less'] 
}) 

export class SignUpComponent { 
    imgPath = 'assets/images/'; 
    //acInput = document.getElementById('jobTitle'); 

    @Input() jobTitle : string; 


    autoCompleteKeypress() { 
     if (this.jobTitle == 'bar' || this.jobTitle == 'Bar'){ 
     alert('BOO!'); 
    } 
} 

很新的Angular2和打字稿一般,所以任何想法表示讚賞。謝謝!

+0

在js上添加一個運行示例小提琴,plunker,jsbin或你的替代品,所以其他人不必複製粘貼你的代碼。 – NikosKeyz

+0

你想顯示div而用戶在文本框中輸入一定的時間嗎? – CharanRoot

回答

1

如果你需要做的就是隱藏和顯示div基於特定的輸入值,我會建議你利用基本Two-way binding機制與NgIf Directive類似如下

<input type="text" [(ngModel)]="jobTitle" id="jobTitle" name="autocomplete" placeholder="Job Title" value="" > 
<div *ngIf="jobTitle === 'bar' || jobTitle === 'Bar'"> 
    Contain to display 
</div> 
+0

謝謝大家的答案。決定使用ngif而不是使用組件中的函數。 – devon93

1

通過分配給id,我們沒有將輸入值輸入到this。你需要使用NgModel。但在這種情況下,您並不需要添加到類變量中。

更改HTML這樣的:

<input type="text" id="jobTitle" 
(click)="autoCompleteClick()" 
(keypress)="autoCompleteKeypress($event)" name="autocomplete" 
placeholder="Job Title" value="" > 

內部組件

autoCompleteKeypress(event) { 
    const jobTitle = event.target.value; 
    if (jobTitle == 'bar' || jobTitle == 'Bar'){ 
     alert('BOO!'); 
    } 
}