ChatGPT解决这个技术问题 Extra ChatGPT

从父类调用子组件方法 - Angular

我创建了一个子组件,它有一个我想要调用的方法。

当我调用此方法时,它只触发 console.log() 行,它不会设置 test 属性?

下面是我的更改的快速启动 Angular 应用程序。

家长

import { Component } from '@angular/core';
import { NotifyComponent }  from './notify.component';

@Component({
    selector: 'my-app',
    template:
    `
    <button (click)="submit()">Call Child Component Method</button>
    `
})
export class AppComponent {
    private notify: NotifyComponent;

    constructor() { 
      this.notify = new NotifyComponent();
    }

    submit(): void {
        // execute child component method
        notify.callMethod();
    }
}

孩子

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'notify',
    template: '<h3>Notify {{test}}</h3>'
})
export class NotifyComponent implements OnInit {
   test:string; 
   constructor() { }

    ngOnInit() { }

    callMethod(): void {
        console.log('successfully executed.');
        this.test = 'Me';
    }
}

如何也设置 test 属性?

您可以在此处查看此答案:stackoverflow.com/a/53057589/6663458

M
Muhammad Mabrouk

您可以使用 @ViewChild 来执行此操作以获取更多信息,请查看此 link

带类型选择器

子组件

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

父组件

@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild(ChildCmp) child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

带字符串选择器

子组件

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

父组件

@Component({
  selector: 'some-cmp',
  template: '<child-cmp #child></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild('child') child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

我遵循了您的方法,但是在使用指令时出现错误:[ChildCmp],错误说:指令'在'组件'类型中不存在。我用谷歌搜索了它,发现指令在 rc5 中已被弃用。那么如何在较新的版本上处理它。请帮忙。
试试这个链接 angular.io/guide/component-interaction 并评论指令链接
当有多个同班孩子时如何使其工作?
@rashfmnb“预期声明”。当我尝试在组件中编写 @ViewChild('child') child:ChildCmp; 时出现错误。请帮忙!而且我也无法在指令中导入相同的内容,它给了我类似“指令:(typeof EmployeeProfileC ...”的错误不能分配给“组件”类型的参数。对象文字只能指定已知属性,而“指令”不存在于“组件”类型中。”
这是一个正确的答案,但它会产生紧密耦合的组件。更好的模式是使用 Input 属性:一个可观察对象,孩子通过调用其 自己的 内部函数对其做出反应。见 user6779899 的回答
A
Aljosha Koecher

我认为最简单的方法是使用主题。在下面的示例代码中,每次调用“tellChild()”时都会通知孩子。

父组件.ts

import {Subject} from 'rxjs/Subject';
...
export class ParentComp {
  changingValue: Subject<boolean> = new Subject();
        
  tellChild() {
    this.changingValue.next(true);
  }
}

Parent.component.html

<my-comp [changing]="changingValue"></my-comp>

Child.component.ts

...
export class ChildComp implements OnInit{
  @Input() changing: Subject<boolean>;
  
  ngOnInit(){
    this.changing.subscribe(v => { 
      console.log('value is changing', v);
    });
  }
}

Stackblitz 上的工作示例


这是一个优雅的解决方案,但它并非在所有情况下都能正常工作,可能是由于 Angular 更改检测无法从订阅中正常工作。
发现这是我用例的最佳解决方案。奇迹般有效。谢谢!
整洁的 !对于更简单的情况,您可以通过将具有回调方法的对象传递给子对象来避免主题/订阅开销。与上述类似,子进程会覆盖回调以接收来自父进程的指示。
@shr 你有没有机会分享你的解决方案来传递一个带有回调的对象?
这是一个优雅的解决方案,这应该是公认的答案,只需将导入方法更改为 import {Subject} from 'rxjs';
R
Reinstate Monica

这对我有用!对于 Angular 2,在父组件中调用子组件方法

父组件.ts

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ChildComponent } from '../child/child'; 
    @Component({ 
               selector: 'parent-app', 
               template: `<child-cmp></child-cmp>` 
              }) 
    export class parentComponent implements OnInit{ 
        @ViewChild(ChildComponent ) child: ChildComponent ; 

        ngOnInit() { 
           this.child.ChildTestCmp(); } 
}

Child.component.ts

import { Component } from '@angular/core';
@Component({ 
  selector: 'child-cmp', 
  template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> ` 
})
export class ChildComponent {
  test: string;
  ChildTestCmp() 
  { 
    this.test = "I am child component!"; 
  }
 }


此行中的 ChildVM 是什么:@ViewChild(ChildComponent) child: ChildVM;
@WaleedShahzaib 我认为 OP 的意思是 ChildVMChildComponent
我认为这会创建一个单独的组件实例,但它实际上从您的实例调用函数,它的变量处于该组件的当前状态,天哪!这种方法比第一个答案好得多!
我总是得到“this.child”的未定义值
我对“this.child”未定义的猜测是,ViewChild 指向模板中不存在的东西,或者您试图在生命周期中过早访问它,例如在构造函数中。
H
Hemant Ramphul

Angular – 在父组件的模板中调用子组件的方法

你有 ParentComponent 和 ChildComponent 看起来像这样。

父组件.html

https://i.stack.imgur.com/40D0r.png

父组件.ts

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  constructor() {
  }
}

child.component.html

<p>
  This is child
</p>

child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor() {
  }

  doSomething() {
    console.log('do something');
  }
}

发球时,它看起来像这样:

https://i.stack.imgur.com/rnywq.png

当用户关注 ParentComponent 的输入元素时,您想调用 ChildComponent 的 doSomething() 方法。

只需这样做:

给 parent.component.html 中的 app-child 选择器一个 DOM 变量名称(前缀为 # – hashtag),在这种情况下我们称之为 appChild。将表达式值(您要调用的方法)分配给输入元素的焦点事件。

https://i.stack.imgur.com/jixZC.png

结果:

https://i.stack.imgur.com/qC1Cg.gif


好的,但我们也想使用 ts 以编程方式进行
从组件内使用:@ViewChild('appChild', { static: false }) appChild: ElementRef<HTMLElement>; 和以后使用 this.appChild.doSomething()
s
shr

user6779899 的回答很简洁,更通用但是,根据 Imad El Hitti 的要求,这里提出了一个轻量级的解决方案。这可以在子组件仅与一个父组件紧密连接时使用。

父组件.ts

export class Notifier {
    valueChanged: (data: number) => void = (d: number) => { };
}

export class Parent {
    notifyObj = new Notifier();
    tellChild(newValue: number) {
        this.notifyObj.valueChanged(newValue); // inform child
    }
}

Parent.component.html

<my-child-comp [notify]="notifyObj"></my-child-comp>

Child.component.ts

export class ChildComp implements OnInit{
    @Input() notify = new Notifier(); // create object to satisfy typescript
    ngOnInit(){
      this.notify.valueChanged = (d: number) => {
            console.log(`Parent has notified changes to ${d}`);
            // do something with the new value 
        };
    }
 }

l
lwairore

考虑以下示例,

import import { AfterViewInit, ViewChild } from '@angular/core';
import { Component } from '@angular/core';
import { CountdownTimerComponent }  from './countdown-timer.component';

@Component({
    selector: 'app-countdown-parent-vc',
    templateUrl: 'app-countdown-parent-vc.html',
    styleUrl: [app-countdown-parent-vc.css]
})
export class CreateCategoryComponent implements OnInit, AfterViewInit {
    @ViewChild(CountdownTimerComponent, {static: false}) private timerComponent: CountdownTimerComponent;
    ngAfterViewInit() {
        this.timerComponent.startTimer();
    }

    submitNewCategory(){
        this.ngAfterViewInit();
    }
}

Read more about @ViewChild here


这是最好的答案。
无需显式调用 ngAfterViewInit()。如果在类上实现,它将被自动调用
需要显式调用 ngAfterViewInit(),因为我们显式需要告诉 Angular 调用方法 startTimer(),该方法位于组件 CountdownTimerComponent
M
Manjunath Hadimani

父组件.html

<app-child #childComponent></app-child>

父组件.ts

@Component({
    selector: 'app-parent',
    templateUrl: './app-parent.component.html',
    styleUrls: ['./app-parent.component.scss']
})
export class ParentComponent {
    @ViewChild('childComponent', {static: false}) childComponent: ChildComponent;

    anyMethod(): void {
        childComponent.updateData() // updateData is a child method
    }
}

child.component.ts

@Component({
    selector: 'app-child',
    templateUrl: './app-child.component.html',
    styleUrls: ['./app-child.component.scss']
})
export class ChildComponent {
    updateData(): void {
      // Method code goes here
    }
}

V
Vibhor Dube

我有一个确切的情况,即父组件在表单中有一个 Select 元素,并且在提交时,我需要根据从选择元素中选择的值调用相关的子组件的方法。

父.HTML:

<form (ngSubmit)='selX' [formGroup]="xSelForm">
    <select formControlName="xSelector">
      ...
    </select>
<button type="submit">Submit</button>
</form>
<child [selectedX]="selectedX"></child>

家长.TS:

selX(){
  this.selectedX = this.xSelForm.value['xSelector'];
}

儿童.TS:

export class ChildComponent implements OnChanges {
  @Input() public selectedX;

  //ngOnChanges will execute if there is a change in the value of selectedX which has been passed to child as an @Input.

  ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
    this.childFunction();
  }
  childFunction(){ }
}

希望这可以帮助。