当前位置:网站首页>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;
};
}


边栏推荐
- Look at the most influential infrastructure m-dao of Web3 through the current situation of Dao
- Mysql database advanced
- Golang implements sanggi diagram and analyzes user behavior trajectory
- [wechat applet development] (III) homepage banner component uses swiper
- Upload and insert the execle table into the database based on ThinkPHP
- Stack / heap / queue question brushing (Part 2)
- Chinese brands in the historical process
- Cososcreator upgrade gradle version
- 「题解」零钱兑换
- [wechat applet development (II)] custom navigation bar
猜你喜欢

Play to earn: a new and more promising game paradigm in the future

图新地球:如何导入修改了高程基准(椭球)的CAD文件
![[Linux] Oracle VirtualBox installation CentOS 8](/img/fc/ea1070b93d3f1dbc52e60045834ea9.png)
[Linux] Oracle VirtualBox installation CentOS 8

Draw a circular radar chart with canvas

Figure storage geabase
In the next bull market, can platofarm, the leading project in the Web3 world, set foot on the top of the mountain

Is gamefi in decline or in the future?

From starfish OS' continued deflationary consumption of SFO, the value of SFO in the long run

Wargames NATAS (0-10) problem solving essay

Enterprises love hybrid app development, and applet container technology can improve efficiency by 100%
随机推荐
[MySQL] installation tutorial and master-slave configuration
Wechat official account configures custom menu jump applet and automatically replies to jump applet
MySQL date formatting
Vscode code style notes (vetur)
JQ native write bullet frame mask layer
Precautions for using kettle excel input
Wechat applet file types and functions
【一起上水硕系列】Final RAD-new literacies
Figure storage geabase
「题解」蝙蝠侠的麻烦
Web3≠NFT? A digital Renaissance?
Why does the metauniverse need NFT?
Figure New Earth: how to import CAD files with modified elevation datum (ellipsoid)
[shutter] the shutter doctor reports an error
WordPress free theme: document, making reading more convenient
Assembly | screen display numbers
Golang implements sanggi diagram and analyzes user behavior trajectory
Several development frameworks based on openresty
Using golang to implement RPC (1)
Go: how to gracefully time out