@ViewChild не работает в родительском компоненте - PullRequest
0 голосов
/ 21 февраля 2020

Родительский компонент:

import { Component, OnInit, ViewEncapsulation, ViewChild} from '@angular/core';
    import { WelcomeInformationComponent } from '../welcome-information/welcome-information.component';
@Component({
   selector: 'app-nagivation',
   templateUrl: './nagivation.component.html',
   styleUrls: ['./nagivation.component.css'],
   encapsulation: ViewEncapsulation.None
 })
    export class NagivationComponent implements OnInit {
      step = 'step1';
      @ViewChild(WelcomeInformationComponent) child: WelcomeInformationComponent;
    }

Дочерний компонент:

    import { Component, OnInit, Input} from '@angular/core';
    import { NagivationComponent } from '../nagivation/nagivation.component';
@Component({
  selector: 'app-welcome-information',
  templateUrl: './welcome-information.component.html',
  styleUrls: ['./welcome-information.component.css']  
})
    export class WelcomeInformationComponent implements OnInit {
        @Input() step;

        steps():void{
          this.step = 'step2';
          console.log(this.step);

        }    
    }

Родительский компонент html:

<ul>
        <li><a routerLinkActive="active" [ngClass]="(step=='step1')?'active':'visited'" [routerLink] = "'/welcome-information'">Welcome Information</a></li>
       <li><a routerLinkActive="active" class="disable" [routerLink] = "'/your-plan'">Select Your Plan</a></li>
       <li><a routerLinkActive="active" class="disable" [routerLink] = "'/your-data'">Confirm Your Data</a></li>
       <li><a routerLinkActive="active" class="disable" [routerLink] = "'/bank-draft'">Bank Draft</a></li>
       <li><a routerLinkActive="active" class="disable" [routerLink] = "'/your-choice'">Finalize Your Choice</a></li>
</ul>

Здесь я хочу "шаг" "свойство переменной в мой родительский компонент. Таким образом, я могу изменить цвет текста ссылки соответственно. Вместо этого я получаю сообщение об ошибке «undefined», когда пытаюсь консольно записать в журнал свойство «step» в родительском компоненте.

Я новичок в angular. Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

0 голосов
/ 21 февраля 2020

Я бы предложил использовать для этого события маршрутизатора. Вы можете подписаться на любые изменения и соответственно изменить свой стиль.

constructor(private _router: Router) {
    _router.event.subscribe(event => {
        // look at the url and style accordingly.
        if(event instanceof NavigationEnd) {
             if(event.url == 'step-1') {this.active = 'step1'}
        }
    })
}

0 голосов
/ 21 февраля 2020

Лучшим решением для вашей потребности было бы создание выделенного сервиса, назовем его WelcomeInformationService, со свойством steps (оно будет хранить информацию, которую свойство WelcomeInformationComponent steps должно сделать хранить).

Введите службу как в WelcomeInformationComponent, так и в NagivationComponent, и они смогут общаться через нее.

...