我试图在组件初始化后在输入字段中选择一些文本。我知道我可以用 a 来做到这一点setTimeout(),但这感觉有点太老套了。
大多数挂钩在通过双向绑定加载输入文本之前运行。每当有人选择其他字段时,其他字段也会运行。
代码: https: //stackblitz.com/edit/angular-pxrssq
import { Component, OnInit, Input, ViewChild } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<input #input type="text" [(ngModel)]="info.one"/>
<input type="text" [(ngModel)]="info.two"/>`,
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() info;
@ViewChild('input', {static: true} ) input;
constructor() { }
ngOnInit() {
this.input.nativeElement.select();
}
}
Run Code Online (Sandbox Code Playgroud)
是否有一个生命周期钩子在组件初始化后但在双向绑定加载后运行一次?
我正在尝试理解并尝试 Angular 生命周期挂钩。
关于ngOnDestroy,在官方文档中是这样说的:
当指令、管道或服务被销毁时调用的生命周期挂钩。用于实例销毁时需要进行的任何自定义清理。
因此,我可以ngOnDestroy在重定向页面时触发该事件。ngOnDestroy奇怪的是,当我重新加载页面时,我无法触发。当我重新加载页面时,它不会破坏我的指令和服务吗?为什么ngOnDestroy页面重新加载时不触发?
Tslint 正在发送警告,指示OnChanges应该为方法生命周期挂钩实现ngOnChagnes。如果我更改ngOnChanges为OnChanges则警告不存在。
import { Component, Input, OnInit, Output, EventEmitter, SimpleChange, OnChanges } from '@angular/core';
import { Order } from '../../../../core/orders';
import { CartItem } from '../../../../core/orders';
import { User } from '../../../../core/auth/_models/user.model';
declare var $: any;
@Component({
selector: 'app-order-summary',
templateUrl: './order-summary.component.html',
styleUrls: ['./order-summary.component.scss']
})
export class OrderSummaryComponent implements OnInit, OnChanges {
@Input() cartDetails: Order;
@Input() sellerDetail: User;
@Input() productCost: number;
@Output() closeOrderSummary = new EventEmitter<string>();
@Output() checkoutCart = new EventEmitter<string>();
@Output() updateItemQty …Run Code Online (Sandbox Code Playgroud) 我实际上正在研究 Angular,我想知道是否有办法知道图像是否已正确加载到 dom 中。我尝试使用this.image.nativeElement.width,但宽度是在图像加载之前发送的。
超文本标记语言
<img #image [src]="imagePath">
Run Code Online (Sandbox Code Playgroud)
TS
@ViewChild('image', {static: true})
image: ElementRef<HTMLImageElement>;
Run Code Online (Sandbox Code Playgroud)