Reputation: 127
I am new to angular and i am trying to understand why my addEventListener method is not working? What i am trying to do is to create a delete button that deletes a posted array from my input. The array is nested in a mat-card tag and has an element reference that i called with view child in my typescript. The error i am getting is:
ERROR TypeError: Cannot read property 'addEventListener' of undefined at PostsComponent.ngAfterViewInit.
This is the code:
Post Component HTML
<mat-card #cardRef [notes] ="inputField" class="inputField">
<ul>
<li>
{{inputField.name}}
{{inputField.department}}
{{inputField.message}}
</li>
</ul>
<button (click)="removeList()">Delete</button>
</mat-card>
Post Service
export class PostService
public inputField = []
removeDiv(id){
const i = this.inputField.findIndex(res => res.id === id);
if (i !== -1) {
this.inputField.splice(i, 1)
}
}
}
Post Component.ts
export class PostsComponent {
constructor(private Posts: PostService){}
public inputField = [];
list;
ngAfterViewInit(){
this.cardRef.nativeElement.addEventListener('click',
this.removeList.bind(this))
}
removeList(){
this.Posts.removeDiv(this.inputField.id)
}
}
Upvotes: 0
Views: 571
Reputation: 13515
If I understand your problem correctly, you do not want to display the <mat-card>
component after the removeList()
function is run.
Angular is all about building the DOM dynamically based on your state / model. As far as I see it, this is no different. It's not a case of "deleting the element" from the DOM, but rather telling Angular whether or not it should be in the DOM at any given time.
So surely it's just a case of using *ngIf
?
Store the state of whether or not the <mat-card>
should be hidden (default false) in the component, and update that to true when the event handler runs. Bind *ngIf
to this property to allow Angular to remove it from the DOM when true.
component.ts
export class PostsComponent {
hideList = false;
removeList() {
this.hideList = true;
}
}
component.html
<mat-card *ngIf="!hideList">
<button (click)="removeList()">Delete</button>
</mat-card>
Upvotes: 1