简体   繁体   中英

Angular 5 Deleting object from array in parent component

I am new to angular.

I am making a Quote listing website in Angular 5. The child component "Quotes" is where the user interacts while the array I would like to delete form is in app.component.ts. Each quote is an object in an array and I would like the entire object to be deleted when the delete button is clicked but I just get loads of errors. The current delete button in the "quotes" component html is as follows:

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

My app.component.ts is as follows:

  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)
    }
}
}

My app.component.html is as follows:

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

It does not currently work as adding the delete functions broke something. I am getting the error:

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)

you need EventEmitter that will emit event from your child component

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

child component.ts must be like this

@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
}

and you parent component.ts will be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM