我有一个在页面上重复多次的组件。我正在实现 AutoNumeric 库,需要将选择器传递给该函数。但是,每个组件实例的选择器必须是唯一的,因此第一个实例将是 cssClass-1
,第二个实例是 cssClass-2
,并且组件会知道要查找哪个选择器。
import { Component, ViewChild, OnInit } from '@angular/core';
import { FieldType } from '@ngx-formly/material';
import AutoNumeric from 'AutoNumeric';
@Component({
selector: 'app-form-currency-type',
template: `
<div class="cssClass-1">
<input
matInput
[formControl]="formControl"
[formlyAttributes]="field"
autocomplete="false"
type="text"
/>
</div>
`,
})
export class CurrencyTypeComponent extends FieldType implements OnInit {
ngOnInit() {
const anElement = new AutoNumeric('.cssClass-1 > input', {
allowDecimalPadding: false,
caretPositionOnFocus: "start",
currencySymbol: "£",
decimalPlaces: 0
});
}
}
我找不到将脚本范围限制为组件的此实例的方法,有办法做到这一点吗?
最佳答案
您需要将类名设为 JS 变量,以便可以针对每个实例进行更改。
如果您对随机字符串感到满意,可以使用 a uuid library .
import { Component, ViewChild, OnInit } from '@angular/core';
import { FieldType } from '@ngx-formly/material';
import AutoNumeric from 'AutoNumeric';
const uuidv1 = require('uuid/v1');
@Component({
selector: 'app-form-currency-type',
template: `
<div [ngClass]="cssClass">
<input
matInput
[formControl]="formControl"
[formlyAttributes]="field"
autocomplete="false"
type="text"
/>
</div>
`,
})
export class CurrencyTypeComponent extends FieldType implements OnInit {
// initialize empty by default
public cssClass = '';
ngOnInit() {
// generate new random string
const cssID = uuidv1();
// prefix required as class names can't start with numbers
const cssPrefix = "cur--";
this.cssClass = cssPrefix + cssID.toString();
// use string interpolation
const anElement = new AutoNumeric(`${this.cssClass} > input`, {
allowDecimalPadding: false,
caretPositionOnFocus: "start",
currencySymbol: "£",
decimalPlaces: 0
});
}
}
关于javascript - 每个 Angular 组件的范围类名称和脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57269969/