https://stackblitz.com/edit/angular6-hvk4p8?file=app%2Fapp.component.ts
ngOnInit() {
var closebtns = document.getElementsByClassName("close");
var i;
for (i = 0; i < closebtns.length; i++) {
closebtns[i].addEventListener("click", function () {
this.parentElement.style.display = 'none';
});
}
}
答案 0 :(得分:0)
在给出答案之前,我必须建议您编写有关Angular2的教程,因为很明显,您正在尝试混合并匹配不应一起使用的内容。 Angular官方网站上有很好的教程。
无需尝试document.getElementsByClassName;我这样做的方式是利用ngFor和Angulars的“事件绑定”,而不是通过DOM搜索
在组件中:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular 5';
items = ["volvo","saab","mercedes","audi"];
currentItem;
ngOnInit() {
}
updateCurrent(selected){
this.currentItem = selected;
console.log(this.currentItem);
}
delete(itemSel: any){
console.log(itemSel);
var index = this.items.indexOf(itemSel);
//if (index>-1)
this.items.splice(index, 1);
console.log(this.items)
}
}
在模板中:
<router-outlet></router-outlet>
<select (change)="updateCurrent($event.target.value)">
<option *ngFor="let item of items">{{item}}</option>
</select>
<div class="close" (click)="delete(currentItem)">X</div>