簡體   English   中英

Angular 5從父組件中的數組刪除對象

[英]Angular 5 Deleting object from array in parent component

我是新手。

我正在Angular 5中創建一個報價清單網站。子組件“ Quotes”是用戶互動的地方,而我要刪除的表單數組位於app.component.ts中。 每個引用都是數組中的一個對象,當我單擊刪除按鈕時,我希望刪除整個對象,但我只會收到很多錯誤。 “ quotes”組件html中的當前刪除按鈕如下:

<a href (click)="delete(true)">
        <i class="trash icon"></i>
        Delete
      </a>

我的app.component.ts如下:

  delete(isComplete,index){
if (isComplete){
    let toDelete=confirm(`Are you sure you want to delete ${this.quotes[index]}`)

    if(toDelete){
        this.quotes.splice(index,1)
    }
}
}

我的app.component.html如下:

<div *ngFor="let quote of sortedQuotes(); let i = index" [quote]="quote">
  <app-quote 'deleteQuote($event,i)'>
  </app-quote>
</div>

由於添加刪除功能損壞了某些內容,因此當前不起作用。 我收到錯誤消息:

Uncaught Error: Template parse errors:
Unexpected closing tag "app-quote". It may happen when the tag has 
already been closed by another tag. For more info see 
https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have- 
   implied-end-tags (" of sortedQuotes(); let i = index" [quote]="quote">
  <app-quote 'deleteQuote($event,i)'>
  [ERROR ->]</app-quote>
</div>
</div>"): ng:///AppModule/AppComponent.html@18:6
at syntaxError (compiler.js:485)
at DirectiveNormalizer._preparseLoadedTemplate (compiler.js:3220)
at eval (compiler.js:3200)
at Object.then (compiler.js:474)
at DirectiveNormalizer._preParseTemplate (compiler.js:3200)
at DirectiveNormalizer.normalizeTemplate (compiler.js:3178)
at CompileMetadataResolver.loadDirectiveMetadata (compiler.js:14908)
at eval (compiler.js:34412)
at Array.forEach (<anonymous>)
at eval (compiler.js:34411)

您需要EventEmitter將從子組件中發出事件

<app-quote (delete)='deleteQuote($event,i)'>
</app-quote>

component.ts必須是這樣的

@Output() delete:EventEmitter<type> = new EventEmitter<type>();

onDeleteButtonClick() {
  //you need to emit event 
  delete.emit();
  // this can be done from button click mostly, which i am guessing is your case
}

而您的父component.ts將是

deleteQuote(event:type,i:type) {
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM