【问题标题】:Access to the parent value from child component [Angular]从子组件访问父值 [Angular]
【发布时间】:2023-03-27 02:58:01
【问题描述】:

AppComponent(父级)有主页(布局)和页面计数器:

export class AppComponent {
  counter = '1/3';
}

<div class="counter">
  {{counter}}
</div>

还有两个组件(子组件)负责页面的内容。从子组件,需要访问父值(计数器)。

其中一个:

import {AppComponent} from '../app.component';

export class Page1Component {
  app: AppComponent;
}
SomeEvent($event) {
  this.app.counter='2/3';
}

<div class="content">
 ...
</div>

事件发生后我得到一个错误: "TypeError: 无法读取未定义的属性 'counter'"

问题: 如何正确操作父变量?

【问题讨论】:

  • 参考此链接从子组件访问父值:link

标签: angular typescript


【解决方案1】:

您可以通过输入属性将父变量传递给子组件。

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

    export class Page1Component {
      @Input() counter;

    SomeEvent($event) {
      this.counter='2/3';
    }
    }

在您的应用中,您可以通过柜台

app.component.html

<page1 [counter]="counter"><page1>

如果您也想更改父级的计数器,您可以定义一个输出事件发射器并在发生某些事件时调用父级中的方法

更新如果你想更换父母的电脑,你可以试试这个:

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

export class Page1Component {
  @Output() change: EventEmitter<any> = new EventEmitter();

SomeEvent($event) {
  this.change.emit();
}
}

app.component.html

<page1 [change]="counterChanged()"><page1>

app.component.ts

export class AppComponent{
counterChanged() {
this.counter = "whatever value";
}

}

【讨论】:

    【解决方案2】:

    在您的子组件中添加输入字段:

    @Input() counter: any;
    

    然后您可以在父 html 中绑定到此属性:

    <child-component-selector [counter]="counter"></child-component-selector>
    

    【讨论】:

    • ChildComponent 是页面(AppComponent)的内容。在这种情况下,标记将中断。我只想在调用子组件之一时更改计数器。
    【解决方案3】:

    你这样做是错误的,你不能那样做。 您必须通过@Input标签以以下方式执行此操作

    例如:

     export class AppComponent {
       counter = '1/3';
    }
    

    在app组件的html中
    &lt;ChildComponent [counter]="counter"&gt;&lt;/ChildComponent&gt;

    在您的子组件中

    import { Component, Input } from '@angular/core';
    export class ChildComponent{
            @Input() counter:any;
    
             //after this you can use counter
       }
    

    更多信息请联系here

    【讨论】:

    • ChildComponent 是页面(AppComponent)的内容。在这种情况下,标记将中断。我只想在调用子组件之一时更改计数器。
    • 您可以更改选择器。对吗?或者我错了吗?如果我错了,请纠正我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2020-07-10
    • 2019-06-15
    • 2019-11-23
    相关资源
    最近更新 更多