首页 文章

将对象从父级传递给子级

提问于
浏览
0

我有一个约定对象,我必须作为输入传递给子组件,当我在子模板中调用它时显示约定id,但是当我尝试在console.log中使用我的约定时,我得到了未定义 . 我尝试将我的console.log放在子的构造函数中以及ngOnInit,ngAfterViewInit和ngOnChanges中 . 对于ngOnChanges,当我只传递约定的id作为子组件的输入时,它工作正常,但我需要传递约定而不是它的id .

index.component.ts

@Component({
    templateUrl: './index.template.html',
    selector: 'be-convention-update',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ConventionUpdateComponent {

    private convention$: Convention;
    private conventionId: number;

    constructor(private route: ActivatedRoute,
        private conventionService: ConventionService) {
        this.route.params.subscribe(
            (params: any) => {
                this.conventionId = params['id'];
                this.conventionService.getOne(this.conventionId).subscribe(response => this.convention$ = response);
            }
        );
    }

}

index.template.html

<be-form-convention [convention]="convention$"></be-form-convention>

form.component.ts

@Component({
    selector: 'be-form-convention',
    templateUrl: './form.template.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ConventionFormComponent implements OnChanges, OnInit {

    @Input() convention: Convention;

    constructor() {
    }

    public ngAfterViewInit() {
      console.log(this.convention); //undefined
    }

    public ngOnInit(): void {
      console.log(this.convention); //undefined
    }

    public ngOnChanges(changes: SimpleChanges): void {
      const object: SimpleChange = changes.convention;
      console.log('prev value: ', object.previousValue); //undefined
      console.log('got name: ', object.currentValue); //undefined
    }

}

3 回答

  • 0

    根据我的理解,当您收到输入或输入值更改时,您希望执行某些操作 .

    您可以将input指令与set函数一起使用,如下所示:

    _convention: Convention;
    @Input()
    set convention(convention: Convention) {
        this._convention = convention;
        //the code you want to handle after input is received
    }
    
  • 0

    对于组件 - 组件通信,我总是使用服务 .

    我所做的是:我创建一个服务并创建两个函数(getData和setData) .

    当我想要将一些数据从一个组件发送到另一个组件时,我调用setData方法,当我想在其他组件中接收数据时,我使用getData方法 .

    这是一个例子:

    从'@ angular / core'导入;

    @Injectable()
    export class DataExchange {
    
      data; //Global Variable of 'any' type.
    
      setData(data){
    this.data = data;
      }
    
    getData():any{
      return this.data;
    }
    }
    
  • 0

    由于它是一个异步操作,我建议你等到约定获取值时使用 *ngIf 来加载子组件当约定对象不为空时

    <ng-container *ngIf="convention$">
    <be-form-convention [convention]="convention$"></be-form-convention>
    </ng-container>
    

相关问题