typescript @ViewChild - 从父级访问CHILD COMPONENT。当您要在子组件中触发函数时,这非常有用。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript @ViewChild - 从父级访问CHILD COMPONENT。当您要在子组件中触发函数时,这非常有用。相关的知识,希望对你有一定的参考价值。

//We can all use the # ref symbol to ref. any element
//And use Jquery to refrence it as well

//HTML TEMPLATE
<div #refsummernote >Hello Summernote</div>


//COMPONENT
//USE property .nativeElement
@ViewChild('refsummernote') refsummernote: ElementRef;
let $mysummernote = ($(this.refsummernote.nativeElement) as any);  //<--nativeElement

//Print innerHtml, result: "Hello Summernote"
console.log("refsummernote: "+ $(this.refsummernote.nativeElement).html()); 
//We can also do the same thing with a local variable. 
//Instead of trying to load the particular class, we can do: 
//template variable #reference to the child element

import { Component, ViewChild } from '@angular/core';
import { UserProfile } from '../user-profile';

@Component({
  template: '<user-profile #myProfile (click)="update()"></user-profile>'
})
export class MasterPage {
  @ViewChild('myProfile') userProfile: UserProfile
  constructor() { }
  update(){
    this.userProfile.sendData();
  }
}
//When use the user-profile on our parent component, 
//we can reference the UserProfile component class and 
//then assign it to a local property:

import { Component, ViewChild } from '@angular/core';
import { UserProfile } from '../user-profile';

@Component({
  template: '<user-profile (click)="update()"></user-profile>',
})
export class MasterPage {
  // ViewChild takes a class type or a reference name string.
  // Here we are using the type
  @ViewChild(UserProfile) userProfile: UserProfile

  constructor() { }

  ngAfterViewInit() {
    // After the view is initialized, this.userProfile will be available
    this.update();
  }

  update() {
    this.userProfile.sendData();
  }
}
//http://learnangular2.com/viewChild/
//For example, our <user-profile> component can have a method called sendData()
//that needs to be accessed by a parent component.

@Component({
  selector: 'user-profile'
})

export class UserProfile {
  constructor() {}
  sendData() {
    //send data
  }
}

以上是关于typescript @ViewChild - 从父级访问CHILD COMPONENT。当您要在子组件中触发函数时,这非常有用。的主要内容,如果未能解决你的问题,请参考以下文章

typescript @ViewChild - 从父级访问CHILD COMPONENT。当您要在子组件中触发函数时,这非常有用。

使用 ViewChild 访问 MatDrawer 在 Angular 8 中引发错误

TypeScript 中的 querySelectorAll 等效项

Angular 在项目中学习@ViewChild和ElementRef的使用

Angular @ViewChild() 错误:预期 2 个参数,但得到 1 个

@Viewchild 看不到 matSort