我是角色新手,想知道如何操作dom元素,专门选择标记,当用户点击按钮时。
这是我使用的代码:
父组件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-add-recipe',
templateUrl: './add-recipe.component.html',
styleUrls: ['./add-recipe.component.css']
})
export class AddRecipeComponent implements OnInit {
units = [
{ id: 1, name: "test" },
{ id: 2, name: "test1" },
{ id: 3, name: "test2" },
{ id: 4, name: "test3" }
];
constructor() {}
ngOnInit() {
}
addIngredient(object) {
// doing stuff
}
}
父视图:
<input #ingredientName type="text" class="form-control" placeholder="name">
<input #ingredientQty type="text" class="form-control" placeholder="qty">
<app-select-units [units]="units"></app-select-units>
<button type="button" class="btn btn-outline-primary" (click)="addIngredient({ name: ingredientName.value, quantity: ingredientQty.value, unit: chosenUnit }); ingredientName.value=''; ingredientQty.value=''; ingredientUnit.value=''">add</button>
子组件:
import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-select-units',
templateUrl: './select-units.component.html',
styleUrls: ['./select-units.component.css']
})
export class SelectUnitsComponent implements OnInit {
@Input() units: string[];
@Input() selectedUnit: string;
constructor() { }
ngOnInit() {
}
}
子视图:
<select [(ngModel)]="chosenUnit" #ingredientUnit class="form-control" name="selectUnit">
<option value="" [attr.selected]="!selectedUnit ? true : null" disabled>select</option>
<option *ngFor="let unit of units" value="{{ unit.id }}" [attr.selected]="selectedUnit == unit.id ? true : null">{{ unit.name }}
</option>
</select>
当用户点击父组件上的按钮时,它会调用它&#34; addIngredient&#34;方法,并清除两个输入。
我也尝试将选择清除到第一个选项(我知道这样做不可能)。
有没有办法将select绑定到父组件并在按钮单击后清除它?