当前位置:网站首页>Typescript decorator
Typescript decorator
2022-07-24 08:32:00 【lvxinaidou】
1. Define a decorator , The function under the decorator will trigger automatically
app.component.html
<button nz-button nzType="primary" (click)="method(obj)">decorator</button>
app.component.ts
import {
Component, OnInit,} from '@angular/core';
import {
Color } from './core/learn-decorator';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
public title:string = '';
public operate:string = 'add';
constructor() {
}
ngOnInit() {
}
obj = {
name: 'lxing', age: 30}
@Color('red')
method(e) {
console.log(e); // {name: 'lxing', age: 30}
console.log('method!!!!!owner');
}
// selectValue(e) {
// console.log(e);
// }
}
Decorator
export function Color(value:string):Function {
//red
console.log(value);
return function(target:Object, key:string | symbol, descriptor:PropertyDescriptor) {
// {constructor: class AppCompent, ngOnInit(), method: fucntion.....}
console.log(target);
// Function name method()
console.log(key);
// {configuable: true, enumerable: false, value: function()......, writable: true}
console.log(descriptor);
const original = descriptor.value;
descriptor.value = function(...args:any) {
// [{name: 'lxing', age: 30}]
console.log(args);
// There must be these two lines , Only in this way can the external event callback be triggered .
const result = original.apply(this, args);
console.log(result)
return result;
}
return descriptor;
}
}
You can also specify the name of the function , In this way, the triggered function can be placed in any position
The changed code
import {
Component, OnInit,} from '@angular/core';
import {
Color } from './core/learn-decorator';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
public title:string = '';
public operate:string = 'add';
constructor() {
}
ngOnInit() {
}
obj = {
name: 'lxing', age: 30}
@Color('red', 'method')
selectValue(e) {
console.log(e);
}
method(e) {
console.log(e); // {name: 'lxing', age: 30}
console.log('method!!!!!owner');
}
}
export function Color(value:string, methodName: string):Function {
//red
console.log(value);
return function(target:Object, key:string | symbol, descriptor:PropertyDescriptor) {
// {constructor: class AppCompent, ngOnInit(), method: fucntion.....}
console.log(target);
// Function name method()
console.log(key);
// {configuable: true, enumerable: false, value: function()......, writable: true}
console.log(descriptor);
const original = descriptor.value;
descriptor.value = function(...args:any) {
// [{name: 'lxing', age: 30}]
console.log(args);
// There must be these two lines , Only in this way can the external event callback be triggered .
const result = original.apply(this, args);
console.log(result)
return result;
}
return descriptor;
}
}
Use scenarios : Dialog box ,ngOnChanges Encapsulation , Reduce duplicate code
father.html + ts
<input [(ngModel)]="title"/>
<app-child [title]="title" [operate]="operate"></app-child>
public title:string = '';
public operate:string = 'add';
child.html + ts
<h1>{
{
title}}--{
{
operate}}</h1>
import {
Component, OnInit, Input, OnChanges } from '@angular/core';
import {
TrackChanges } from 'src/app/core/learn-decorator';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnChanges {
@Input() title : string = '';
@Input() operate: string = '';
@TrackChanges('title', 'changeDetails')
ngOnChanges() {
console.log('do some operate!!!');
}
changeDetails() {
console.log('value change');
// this.title = 'title'
}
}
Decorator
export function TrackChanges<Type>(key: string, methodName: string): Function {
return function (targetClass, functionName: string, descriptor): Function {
const source = descriptor.value;
descriptor.value = function (changes: SimpleChanges): Function {
console.log(changes);
if (changes && changes[key] && changes[key].currentValue !== undefined) {
console.log(targetClass);
console.log(targetClass[methodName]);
targetClass[methodName].call(this, changes[key].currentValue as Type);
}
return source.call(this, changes);
};
return descriptor;
};
}


边栏推荐
- Recognition and storage of Graphs
- 「题解」零钱兑换
- Hack the box - Web requests module detailed Chinese tutorial
- Wechat official account configures custom menu jump applet and automatically replies to jump applet
- [JDBC] classic interview questions of JDBC, constantly updating
- Wechat applet host environment, applet architecture, concise operation structure
- Use the bark app to realize the process of pushing messages to mobile phones
- 【一起上水硕系列】Final RAD-new literacies
- SQL learning
- Shanghai issued a document to support the entry of NFT cultural exchange: the trend of digital collections has arrived!
猜你喜欢

Four data interaction modes of go grpc

【一起上水硕系列】Final RAD-new literacies

Digital collections "chaos", 100 billion market changes are coming?

国产“火箭心”人工心脏上市 不同人工心脏有什么区别?

Wechat applet host environment, applet architecture, concise operation structure

3587. 连通图(吉林大学考研机试题)

"Move to earn" motion metauniverse, move starts a new journey

Precautions for using kettle excel input
![[MySQL] installation tutorial and master-slave configuration](/img/79/0ad3f68b69a0a03a62422d4cc70035.png)
[MySQL] installation tutorial and master-slave configuration

Figure storage geabase
随机推荐
mysql SUBSTRING_ Application of index in business scenarios
Using golang to implement RPC (1)
[wechat applet development] (II) wechat native bottom tabbar configuration
Shanghai issued a document to support the entry of NFT cultural exchange: the trend of digital collections has arrived!
The code is tired. Stop and enjoy the top color matching~
「题解」火神之友
Vscode code style notes (vetur)
Advantages and disadvantages of redis and ZK implementing distributed locks
FPGA integrated project - image edge detection system
Okaleido tiger NFT is about to log in to binance NFT platform, and the era of NFT rights and interests is about to start
Web3 traffic aggregation platform starfish OS interprets the "p2e" ecosystem of real business
How difficult is it to build a digital collection platform?
栈/堆/队列刷题(下)
Move protocol launched a beta version, and you can "0" participate in p2e
Private traffic + apps, new opportunities for e-commerce drainage
Wechat applet subscription message development process
Wxml template concise tutorial
【一起上水硕系列】一起提前看看July课程
The beta version of move protocol is stable, and it is temporarily decided to expand the scale of the prize pool
Figure New Earth: how the RVT format BIM model modeled by Revit can accurately match the map with texture