我有一个角度为2的UI。我在组件模板中定义了一个文本区域,我尝试使用@ViewChild批注获取对该文本区域的引用。但是,它返回undefined。我知道原因,但不知道如何解决此问题。问题出在
这是我在html组件中的文本区域
<textarea id="messageTxt" formControlName="message" rows="6" [placeholder]="'PLACEHOLDERS.MESSAGE' | translate" #messageTxt></textarea>
所以我要从组件ts文件中粘贴部分代码,如下所示。 messageTextArea原来是未定义的。我猜这是因为ngOnInit方法,我们正在等待创建表单,直到我们从服务获得响应为止。知道如何重写代码,以便可以在messageTextArea变量中获得适当的引用。
export class SmsTemplateFormComponent implements OnInit,AfterViewInit {
@ViewChild('messageTxt') messageTextArea: ElementRef;
constructor(
private fb: FormBuilder,
private templatesService: TemplatesService,
private configService: ConfigService,
private accountService: AccountsService
) {}
ngAfterViewInit() {
fromEvent(this.messageTextArea.nativeElement,'keyup').pipe(
map( (e: KeyboardEvent) => (e.target as HTMLTextAreaElement).value),
debounceTime(10),
distinctUntilChanged(),
switchMap( (value) => this.templatesService.retrieveSmsSegmentCount(value) )
).subscribe(
response => {
this.segmentCount = response.segmentCount;
}
);
}
ngOnInit() {
this.isFormLoading = true;
this.accountService.get(this.account.id).subscribe(
(value) => {
this.account = value;
this.isFormLoading = false;
this.messagePrefix = value.messagePrefix;
this.formGroup = this.fb.group(
{
defaultTemplate: [this.defaultInitialValue],
language: [null, Validators.required],
message: [ this.messagePrefix ? this.messagePrefix:'', [Validators.required]],
longUrl: ['']
},
{
validator: [
hasUrlTagValidator(TemplatesService.urlTag),
messagePrefixSMSValidator(this.messagePrefix? this.messagePrefix: null, 'message')
]
}
);
combineLatest(
this.messageControl.valueChanges,
this.urlControl.valueChanges
).subscribe(([message, url]) => {
const { html, length } = this.templatesService.compileSmsTemplate(
message,
url ? this.placeholderUrl : ''
);
this.messageHtml = html;
this.messageLength = length;
});
if (this.template) {
this.formGroup.setValue({
defaultTemplate: this.template.defaultTemplate,
language: this.template.language,
message: this.template.text,
longUrl: this.template.longUrl
});
}
this.urlControl.valueChanges.subscribe(() => {
const messageValue: string = this.messageControl.value;
if (!messageValue || !messageValue.includes(TemplatesService.urlTag)) {
this.messageControl.setValue(messageValue + TemplatesService.urlTag);
}
});
this.templatesService.retrieveSmsSegmentCount(this.messageControl.value)
.subscribe( response => {
this.segmentCount = response.segmentCount;
});
}
);
}
}
答案 0 :(得分:0)
您确实不需要fromEvent
。您可以将keyup
事件绑定到您的文本区域:
<textarea id="messageTxt" formControlName="message" rows="6" [placeholder]="'PLACEHOLDERS.MESSAGE' | translate" (keyup)="doStuff(messageTxt.value)" #messageTxt></textarea>
然后在您的组件中:
doStuff(value: string) {
// do whatever with the value
}