html - 选择垫选项( Angular )时如何调用方法?

标签 html angular typescript binding angular-material

我是 Angular 的新手,我想调用一个特定的方法,只有在选择了选项 3 时。 我正在努力解决这个问题,但在互联网上找不到太多相关信息。

当我调用选项 3 时,输出为空。

到目前为止,这是我的代码:

应用程序组件.html:

<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select [(value)]="selected" >
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option selectionChange="greet($event)">Option 3</mat-option>
  </mat-select>
</mat-form-field>

<p>You selected: {{selected}}</p>

应用程序组件.ts:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'materialdesign';
  selected = 'option33';


  greet() {
    this.selected = 'it works';
  }
}

最佳答案

试试这个

<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select [(value)]="selected" (selectionChange)="inputChange()">
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 3</mat-option>
  </mat-select>
</mat-form-field>

<p>You selected: {{selected}}</p>

在 component.ts 中

title = 'materialdesign';
  selected = 'option33';
inputChange(){
  if(this.selected == 'option3'){
    this.greet();
  }
}

  greet() {
    this.selected = 'it works';
  }

stackblitz example

关于html - 选择垫选项( Angular )时如何调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59644947/

相关文章:

java - 基于多个正则表达式规则插入字符串的算法

http - ionic 2/Angular 2/CORS : HTTP Headers not being sent with request

Angular 2 : trouble in integrating ng2-select

javascript - 是否可以使用 HTML5 或 jquery 中的坐标在网页中进行导航?

html - 将另一口井定位在父容器的中心

html - 使用 span 在 li 元素中塑造文本

angular - 如何正确处理和控制Angular和Web API中的错误-2

javascript - Angular 2 : generating checkboxes issue

angular - 错误错误 : The requested path contains undefined segment at index 1

javascript - 在初始化时运行程序