I'm just learning Angular and I'm having trouble passing a method to another component.
Object Item has Array of documents and I would like to delete document with given id
api / item / {itemId} / deleteDocument / {documentId}. This endpoint comes from springboot backend and delete document from item array from database.
This is it what i have:
item.service.ts
@Injectable({
providedIn: 'root'
})
export class ItemService {
private serviceUrl = 'api/item/';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private http: HttpClient) {}
deleteDocument(itemId: number, documentId: number): Observable<any>{
return this.http.delete(this.serviceUrl + itemId +'/deleteDocument/' + documentId).pipe();
}
item-component.ts
Here i would like to delete document from document list in Item.
export class ItemComponent implements OnInit {
item: ItemElem = new ItemElem();
constructor(private itemService: ItemService, public route: ActivatedRoute) { }
ngOnInit(): void {
const id = this.route.snapshot.paramMap.get('id');
this.itemService.getById(id).subscribe(p => {
this.item = p;
});
this.itemService.getDocumentList(id).subscribe(docList => {
this.item.documents = docList;
});
}
onDeleteDocument(document: DocumentListItem) {
this.itemService.deleteDocument(this.item.id, document.id).subscribe(p => {
this.item.documents = this.item.documents.filter(
doc => doc.id !== document.id);
});
}
document-list-component.ts
deleteItem(element) {
// HERE
}
private prepareDocumentActions() {
return [
{
name: 'edit',
makeAction: (elem: DocumentListItem) => {
window.open(elem.documentOpenUrl);
}
{
name: 'delete',
makeAction: (elem: DocumentListItem) => {
this.deleteItem(elem.id);
}
},
];
}
and html:
<div fxLayout="row" fxLayoutAlign="space-around none" >
<div *ngFor="let action of documentActions">
<button mat-icon-button color="primary" (click)="action.makeAction(element)">
<mat-icon class="md-24">{{action.name}}</mat-icon>
</button>
</div>
</div>
So, i would like to provide method from item-component.ts to document to document-list-component.ts there where i have deleteDocument() method. In view i have button which after click will be deleted document from documents array in Item and of course from db.
It is probably a trivial task, but I work in java and sprinboot on a daily basis and I do not know Angular. I will be grateful for any help.
Greetings !!
question from:
https://stackoverflow.com/questions/65869874/using-component-method-in-other-component-angular 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…