如何将布尔值从子组件传递到父组件,以便我可以使用该值来启用/禁用同级子组件?

问题描述 投票:0回答:2

我有这个父组件

-person.component.html

<div>
    <main>
        <address-list (addressPresent)="setPersonInfo($event)"></address-list>
        <company-list *ngIf="personInfo"></company-list>
    </main>
</div>

-地址列表.component.ts

addressExists: boolean;
@Output() addressPresent: EventEmitter<boolean> = new EventEmitter<boolean>();

updateAddress(value: boolean) {
    this.addressPresent.emit(value);
}

ngOnInit(): void {
    this.data();
}

data(): void {
    ...
    ...
    this.personService.getPersonInfo(this.personId).subscribe((res => {
       ...
       this.updateAddress(res.body.personInfo);
       ...
    }))
}

-person.component.ts

personInfo: boolean;

setPersonInfo(value: boolean): void {
    this.personInfo = value;
}

如何将布尔值从

address-list
组件传递到
person
组件,以便我可以使用它来启用或禁用
company-list
组件?

当我将其记录在

undefined
中时,我完成的实现会返回
addressExists
变量的
ngOnInit()
值。

angular typescript eventemitter angular-event-emitter
2个回答
0
投票

我不明白你在哪里设置addressExists。您可以在顶部将其定义为布尔值,但不要将其设置为任何值。所以它将是未定义的。


0
投票

如果您正在使用服务,一个建议是在处理订阅的服务中只包含一个可观察对象。像这样:

person.service.ts:

@Injectable({
  providedIn: 'root'
})
export class PersonService {

  private personSelectedSource: Subject<boolean> = new Subject<boolean>();
  personSelected$ = this.personSelectedSource.asObservable();

  constructor() { }

  setPersonSelected(selected: boolean) {
    this.personSelectedSource.next(selected);
  }

}

地址列表.component.ts:

constructer(private personService: PersonService) { }

// This would be your method that is called when a person/address is selected
selectPerson(person: any) {
  this.personService.setPersonSelected(person == null ? false : true);
}

person.component.ts:

constructor(private personService: PersonService) { }

personInfo: boolean = false;

ngOnInit(): void {
  this.personService.personSelected$.subscribe(selected => {
    this.personInfo = selected;
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.