首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

任何在Angular 6中自动调用函数的方法,看起来ng-init都不起作用

在 Angular 6 中,ng-init 指令已被弃用,因此不建议使用它来自动调用函数。相反,你可以使用 Angular 的组件生命周期钩子来实现这个功能。

以下是在 Angular 6 中自动调用函数的几种方法:

  1. 使用 ngOnInit 生命周期钩子:

在组件类中,你可以使用 ngOnInit 生命周期钩子来自动调用函数。ngOnInit 会在组件初始化时自动调用。

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    this.myFunction();
  }

  myFunction() {
    console.log('Function called automatically');
  }
}
  1. 使用 constructor 构造函数:

如果你需要在组件创建时立即调用函数,可以将函数放在构造函数中。

代码语言:javascript
复制
import { Component } from '@angular/core';

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

  constructor() {
    this.myFunction();
  }

  myFunction() {
    console.log('Function called automatically');
  }
}

请注意,如果你的函数依赖于组件的输入属性或其他依赖项,那么在构造函数中调用可能会导致问题。在这种情况下,建议使用 ngOnInit 生命周期钩子。

  1. 使用 @ViewChildAfterViewInit

如果你需要在视图初始化后自动调用函数,可以使用 @ViewChildAfterViewInit 生命周期钩子。

代码语言:javascript
复制
import { Component, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements AfterViewInit {

  @ViewChild('myElement') myElement;

  constructor() { }

  ngAfterViewInit() {
    this.myFunction();
  }

  myFunction() {
    console.log('Function called automatically');
  }
}

在这个例子中,@ViewChild 用于获取视图中的元素,ngAfterViewInit 用于在视图初始化后调用函数。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券