添加条件到ng按键

时间:2017-06-18 17:45:43

标签: angular typescript

当文本输入包含特定值时,我想显示div。

对于我的模板,我有:

<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和Typescript都是新手,所以任何想法都会受到赞赏。谢谢!

2 个答案:

答案 0 :(得分: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!');
    } 
}

答案 1 :(得分:1)

如果你需要做的就是隐藏并根据具体的输入值显示let dest = "\(dico?["adresse"] as? String ?? "") \(dico?["cp"] as? Int ?? 0) \(dico?["ville"] as? String ?? "")" ,我建议您使用Two-way binding基本的NgIf Directive机制,如下所示

div