【问题标题】:function validateTopic(value) not works函数 validateTopic(value) 不起作用
【发布时间】:2019-06-24 20:18:31
【问题描述】:

我想为 app.component.html 中的(模糊)和(更改)调用 app.component.ts 中的方法

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 Code 终端中,

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

【问题讨论】:

  • 你能显示完整的 HTML 代码吗?

标签: javascript html css angular forms


【解决方案1】:

您的 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;
     }
    }

}

【讨论】:

    【解决方案2】:

    这应该可行。

    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);
        }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-29
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多