0

I have this parent component

-person.component.html

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

-address-list.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;
}

How do I pass the boolean value from address-list component to person component so that I can use it to enable or disable the company-list component?

Implementation that I have done returns undefined value for addressExists variable when I log it inside ngOnInit().

cs55
  • 7
  • 4

2 Answers2

0

I don't see where you're setting addressExists. You define it as a boolean at the top, but don't set it to anything. So it will be undefined.

FunkMonkey33
  • 1,956
  • 2
  • 16
  • 24
0

If you are using a service, one suggestion would be to just have an observable in the service that handles the subscription. Like so:

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

}

address-list.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;
  });
}
Zach
  • 640
  • 1
  • 6
  • 16