gpt4 book ai didi

jquery - Angular Directive(指令)发出输出,父级未更新

转载 作者:行者123 更新时间:2023-12-01 04:37:25 24 4
gpt4 key购买 nike

我有一个 Angular 组件,它实际上是一个 Bootstrap 面板。

export class ExerciseComponent implements OnInit {
@Input() exercise:Exercise;
@Input() index:number;
@Input() first:boolean;
@Input() last:boolean;
@Input() active:boolean;
@Input() selected:boolean;
constructor(private data:ApiDataService, private route:ActivatedRoute) {
}

toggleActive(e){
let show = (e.type=='show');
this.active = show;
}
}

使用模板:

<div class="panel-heading">
<div>
<h5 class="panel-title">
<a data-toggle="collapse" data-parent="#accordionexercises"
class="accordion-link" href="#collapse{{ exercise.id }}">
{{ exercise.title }} </a>
</h5>
<div class="pull-right">
<i *ngFor="let n of exercise.difficulty | fill" class="fa fa-star"></i>
</div>
</div>
<exercise-preview [hidden]="active" [e]="exercise"></exercise-preview>
</div>
<div id="collapse{{ exercise.id }}" [ngClass]="{'panel-collapse collapse':true, 'in':selected}"
collapseControl (collapseStatus)="toggleActive($event)">
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<div *ngIf="exercise.image" class="pull-right">
<img src="http://localhost:8000{{ exercise.image.file }}"/>
</div>
<div [innerHtml]="exercise.exText"></div>
</div>
</div>
</div>
</div>

和一个名为 collapseControl 的指令它检测 Bootstrap 崩溃事件(Jquery)并将它们传播到我的组件 collapseStatus($event) :

@Directive({
selector: '[collapseControl]'
})
export class CollapseControlDirective{
@Output() collapseStatus: EventEmitter<any>;

constructor(el: ElementRef) {
this.collapseStatus = new EventEmitter();
Observable
.fromEvent($(el.nativeElement), 'hide.bs.collapse show.bs.collapse')
.subscribe(e=> this.collapseStatus.emit(e));
}
}

一切正常,事件传播到父级,this.active根据事件设置,但 UI 不会更新(请注意 [hidden] 组件上的 <exercise-preview/> 属性)。

如果我简单地改变 (collapseStatus)="toggleActive($event)"(click)="toggleActive($event)"一切正常。这必须与 Angular 变化检测有关,但我无法弄清楚我做错了什么。

最佳答案

Angular 不知道通过 Observable.fromEvent 订阅所做的更改,因为这不会发生在 zone 内。 。您可以使用NgZone在区域内运行代码。例如:

import { NgZone } from '@angular/core';

// ...

constructor(el: ElementRef, ngZone: NgZone) {
this.collapseStatus = new EventEmitter();
Observable
.fromEvent($(el.nativeElement), 'hide.bs.collapse show.bs.collapse')
.subscribe(e => {
ngZone.run(() => this.collapseStatus.emit(e));
});
}

您最好使用例如ng-bootstrap ,如果可以的话,以便在使用可折叠元素等时获得更像 Angular 的体验。

关于jquery - Angular Directive(指令)发出输出,父级未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47983430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com