函数validateTopic(value)不起作用

时间:2019-01-31 11:20:23

标签: javascript html css angular forms

我想在app.component.ts被称为对于(模糊)的方法和(变化)app.component.html

app.component.html

<select (blur)="validateTopic(topic.value)" (change)="validateTopic(topic.value)" required #topic="ngModel" [class.is-invalid]="topic.invalid && topic.touched" class="custom-select" name="topic" [(ngModel)]="userModel.topic">
  <option value='default'>I am interested in</option>
  <option *ngFor="let topic of topics">{{topic}}</option>
</select>

app.component.ts

validateTopic(value)
 {
 if(value==='default')
 {
   this.topicHasError=true;
 }
 else{
   this.topicHasError=false;
 }
}

在VS代码端子短它示出了

ERROR in app/app.module.ts(19,1): error TS2304: Cannot find name 'validateTopic'.
app/app.module.ts(19,15): error TS2304: Cannot find name 'value'.
app/app.module.ts(21,4): error TS2304: Cannot find name 'value'.

在“浏览器”窗口中显示,

app.module.ts:19 Uncaught ReferenceError: validateTopic is not defined
    at Module../src/app/app.module.ts (app.module.ts:19)
    at __webpack_require__ (bootstrap:78)
    at Module../src/main.ts (main.ts:1)
    at __webpack_require__ (bootstrap:78)
    at Object.0 (main.ts:12)
    at __webpack_require__ (bootstrap:78)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.js:1

2 个答案:

答案 0 :(得分:0)

您的app.component.ts应该如下所示:

import { Component } from '@angular/core';
@Component({
    selector: 'whatever',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    validateTopic(value)
    {
     if(value==='default')
     {
       this.topicHasError=true;
     }
     else{
       this.topicHasError=false;
     }
    }

}

答案 1 :(得分:0)

这应该有效。

app.component.html

<select (blur)="validateTopic($event.target.value)" 
(change)="validateTopic($event.target.value)">
<option value='default'>I am interested in</option>
<option *ngFor="let topic of topics">{{topic}}</option>
</select>

app.component.ts

 validateTopic(value) {
    if(value==='default') {

    }
    else
    {     
    console.log(value);
    }
    }