[英]how to call a method when mat-option is selected (angular)?
I am new to Angular and I want to call a specific method, only when option3 is selected.我是 Angular 的新手,我想调用一个特定的方法,只有在选择了 option3 时。 I am struggling to solve this and cannot find much information on this on the internet.我正在努力解决这个问题,但在互联网上找不到太多相关信息。
When I call option3, the output is empty.当我调用 option3 时,输出为空。
Here is my code so far:到目前为止,这是我的代码:
app.component.html: app.component.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>
app.component.ts: app.component.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';
}
}
try this尝试这个
<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>
in component.ts在 component.ts
title = 'materialdesign';
selected = 'option33';
inputChange(){
if(this.selected == 'option3'){
this.greet();
}
}
greet() {
this.selected = 'it works';
}
If you want to listen to an event from an Angular component, you need to add parenthesis around the event:如果要监听来自 Angular 组件的事件,则需要在事件周围添加括号:
<mat-option (selectionChange)="greet($event)">Option 3</mat-option>
Then your should method should start executing.然后你的 should 方法应该开始执行。
Try like below,尝试如下,
selectionChange event is part of mat-select. selectionChange 事件是 mat-select 的一部分。 So Just call the method when you select an option from the list.因此,当您从列表中选择一个选项时,只需调用该方法。 And based on the value of the option selected, execute your required code.并根据所选选项的值,执行所需的代码。
.html .html
<mat-form-field>
<mat-label>Select an option</mat-label>
<mat-select [(value)]="selected" (selectionChange)="greet($event)">
<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>
.ts .ts
selected: string;
greet(event) {
if(event.value === 'option3') {
// Execute the required code
}
}
只需在特定的mat-option
元素上定义click
事件处理程序。
<mat-option value="option3" (click)="greet()">Option 3</mat-option>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.