刷新父组件是在子组件上的按钮按下后怎么做? – Angular

huangapple go评论66阅读模式
英文:

How to refresh the Parent component after a button on child component is pressed? - Angular

问题

以下是翻译好的部分:

我目前正在更新弹出窗口中的配料数量,我希望在弹出窗口关闭时重新渲染配料卡并显示新的数量,但我不确定如何实现这一点。

这是我的配料服务代码:

//UPDATE
updateAmount(id: string, newAmount: number): Observable<Ingrediant>{
  return this.http.put<Ingrediant>(`${this.url}/${id}`, {amount: newAmount});
}

这是配料组件的HTML:

<div class="ingrediant-slider">
    <hr>
    <h4 class="ingrediant-heading">Bread</h4>
    <div class="carousel">
        <img src="../../assets/arrows/left-arrow.png" class="arrow-left" (click)="scroll(-scrollAmount)">
        <img src="../../assets/arrows/right-arrow.png" class="arrow-right" (click)="scroll(scrollAmount)">
        <div class="card" *ngFor="let breadIngrediants of breadIngrediants; let i=index">
            <div class="top-circle">
                <h4>{{breadIngrediants.amount}}</h4>
            </div>
            <div class="circle">
                <img [src]="breadIngrediants.image" class="card-img" alt="Image of burger">
            </div>
            <h3>{{breadIngrediants.name}}</h3>
            <button (click)="showPopup = true; selectedIngrediants = breadIngrediants">Update</button>
        </div>
    </div>
</div>

<app-popup *ngIf="showPopup" [selectedIngrediants]="selectedIngrediants" (close)="showPopup = false" (updated)="onUpdate()"></app-popup>

这是配料的.ts文件:

// 将此方法添加到在事件被触发时更新配料列表
onUpdate() {
  // 重新获取配料数据并更新本地变量
  this.ingrediantService.items$.subscribe((data) => {
    this.breadIngrediants = data;
    console.log(data);
    this.cdr.detectChanges();
  });
}

这是弹出窗口的HTML:

<div class="popup" [style.top.px]="getYPosition(selectedIngrediants)">
    <div class="left-pannel">
        <div class="circle">
            <img [src]="selectedIngrediants.image" class="card-img" alt="Image of burger">
        </div>
    </div>
    <div class="right-pannel"></div>
    <h2>{{ selectedIngrediants.name }}</h2>
    <p>{{ getDescription() }}</p>
    <h4>Amount</h4>
    <input type="number" matInput placeholder="0" color="accent" [value]="selectedIngrediants.amount" (change)="detectAmountChange($event)"> 
    <button class="primary-btn" (click)="updateAmount(selectedIngrediants._id!); closePopup();">Update</button>
    <button class="secondary-btn" (click)="closePopup()">Cancel</button>
</div>

这是弹出窗口的.ts文件:

// 将newAmountPlaceholder更改为当前输入值
detectAmountChange(e: any){
  this.newAmountPlaceholder = +e.target.value
}

@Output() updated: EventEmitter<void> = new EventEmitter<void>();

updateAmount(id: string) {
  this.ingrediantService.updateAmount(id, this.newAmountPlaceholder).subscribe((selectedIngrediant) => {
    console.log(selectedIngrediant.amount);
    this.updated.emit(); // 在更新成功时发出事件
  });
}
英文:

so I am currently updating an ingredient amount in a pop-up and I want the ingredient card to rerender and show the new amount when the pop-up closes, however, I am unsure of how to achieve this.

This is my ingredient service code:

  //UPDATE
  updateAmount(id: string, newAmount: number): Observable&lt;Ingrediant&gt;{
    return this.http.put&lt;Ingrediant&gt;(`${this.url}/${id}`, {amount: newAmount});
  }

This is the ingredient component HTML:

    &lt;div class=&quot;ingrediant-slider&quot;&gt;
        &lt;hr/&gt;
        &lt;h4 class=&quot;ingrediant-heading&quot;&gt;Bread&lt;/h4&gt;

        &lt;div class=&quot;carousel&quot;&gt;
            &lt;img src=&quot;../../assets/arrows/left-arrow.png&quot; class=&quot;arrow-left&quot; (click)=&quot;scroll(-scrollAmount)&quot;&gt;
            &lt;img  src=&quot;../../assets/arrows/right-arrow.png&quot; class=&quot;arrow-right&quot; (click)=&quot;scroll(scrollAmount)&quot;&gt;
            &lt;div class=&quot;card&quot; *ngFor=&quot;let breadIngrediants of breadIngrediants; let i=index&quot; &gt;
                &lt;div class=&quot;top-circle&quot;&gt;
                    &lt;h4&gt;{{breadIngrediants.amount}}&lt;/h4&gt;
                &lt;/div&gt;
                &lt;div class=&quot;circle&quot;&gt;
                    &lt;img [src]=&quot;breadIngrediants.image&quot; class=&quot;card-img&quot; alt=&quot;Image of burger&quot;/&gt;
                &lt;/div&gt;
                &lt;h3&gt;{{breadIngrediants.name}}&lt;/h3&gt;
                &lt;button (click)=&quot;showPopup = true; selectedIngrediants = breadIngrediants&quot;&gt;Update&lt;/button&gt;

            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;app-popup *ngIf=&quot;showPopup&quot; [selectedIngrediants]=&quot;selectedIngrediants&quot; (close)=&quot;showPopup = false&quot; (updated)=&quot;onUpdate()&quot;&gt;&lt;/app-popup&gt;

This is the ingrediant .ts:

// add this method to update the ingredient list when the event is emitted
onUpdate() {
  // re-fetch the ingredient data and update the local variable
  this.ingrediantService.items$.subscribe((data) =&gt; {
    this.breadIngrediants = data;
    console.log(data);
    this.cdr.detectChanges();
  });
}

This is the pop-up HTML:

 &lt;div class=&quot;popup&quot;[style.top.px]=&quot;getYPosition(selectedIngrediants)&quot;&gt;
    &lt;div class=&quot;left-pannel&quot;&gt;
        &lt;div class=&quot;circle&quot;&gt;
            &lt;img [src]=&quot;selectedIngrediants.image&quot; class=&quot;card-img&quot; alt=&quot;Image of burger&quot;/&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;right-pannel&quot;&gt;
        
    &lt;/div&gt;
    &lt;h2&gt;{{ selectedIngrediants.name }}&lt;/h2&gt;
    &lt;p&gt;{{ getDescription() }}&lt;/p&gt;
    &lt;h4&gt;Amount&lt;/h4&gt;
    &lt;input type=&quot;number&quot; matInput placeholder=&quot;0&quot; color=&quot;accent&quot;
    [value]=&quot;selectedIngrediants.amount&quot;
    (change)=&quot;detectAmountChange($event)&quot;
    &gt; 

    &lt;button class=&quot;primary-btn&quot; (click)=&quot;updateAmount(selectedIngrediants._id!); closePopup();&quot;&gt;Update&lt;/button&gt;
    &lt;button class=&quot;secondary-btn&quot;  (click)=&quot;closePopup()&quot; &gt;Cancel&lt;/button&gt;
  &lt;/div&gt;

and the pop-up ts:

//changes newAmountPlaceholder to current input value
detectAmountChange(e: any){
  this.newAmountPlaceholder = +e.target.value
}


@Output() updated: EventEmitter&lt;void&gt; = new EventEmitter&lt;void&gt;();


updateAmount(id: string) {
  this.ingrediantService.updateAmount(id, this.newAmountPlaceholder).subscribe((selectedIngrediant) =&gt; {
    console.log(selectedIngrediant.amount);
    this.updated.emit(); // emit the event when the update is successful
  });
}

答案1

得分: 1

以下是翻译好的内容:

你的代码应该可以工作,尽管它并不是一种很干净的方法。有一点,我猜测弹出窗口在Http请求结束之前被关闭,所以(update)从未被调用。

我建议的是让父组件处理Http请求,而将弹出窗口仅处理输入。

在pop-up.ts文件中:

@Output() updated: EventEmitter<any> = new EventEmitter<any>();

updateAmount(id: string) {
  this.updated.emit({ id: id, amount: this.newAmountPlaceholder });
}

在ingrediant.ts文件中:

onUpdate(popupData: any) {
  this.ingrediantService.updateAmount(popupData.id, popupData.amount).subscribe(() => {
    //保存后刷新
    this.ingrediantService.items$.subscribe((data) => {
      this.breadIngrediants = data;
      console.log(data);
      this.cdr.detectChanges();
    });
  });
}

最后,在ingredient.html文件中更新HTML:

<app-popup *ngIf="showPopup" [selectedIngrediants]="selectedIngrediants" (close)="showPopup = false" (updated)="onUpdate($event)"></app-popup>

希望这有帮助 刷新父组件是在子组件上的按钮按下后怎么做? – Angular

英文:

Your code should work, even though it's not a very clean approach. One thing, I guess the popup is being closed before the end of the Http request so the (update) is never called.

What i recommand is letting the parent component handle the Http Request and leave the Popup to only deal with input.

In pop-up.ts

@Output() updated: EventEmitter&lt;any&gt; = new EventEmitter&lt;any&gt;();


updateAmount(id: string) {
  this.updated.emit({id: id, amount: this.newAmountPlaceholder});

}

In ingrediant.ts:

onUpdate(popupData:any) {
  this.ingrediantService.updateAmount(popupData.id, popupData.amount).subscribe(() =&gt; {
    //after saving refresh
    this.ingrediantService.items$.subscribe((data) =&gt; {
      this.breadIngrediants = data;
      console.log(data);
      this.cdr.detectChanges();
    });
  });
}

and finally update the html in ingerdiant

&lt;app-popup *ngIf=&quot;showPopup&quot; [selectedIngrediants]=&quot;selectedIngrediants&quot; (close)=&quot;showPopup = false&quot; (updated)=&quot;onUpdate($event)&quot;&gt;&lt;/app-popup&gt;

Hope this works 刷新父组件是在子组件上的按钮按下后怎么做? – Angular

huangapple
  • 本文由 发表于 2023年4月13日 19:57:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定