Ввод углового материала не обновляет текст заполнителя - PullRequest
0 голосов
/ 20 октября 2018

Я использую Angular 6 с Material CSS из material.angular.io

Я пытаюсь создать свою директиву, которая будет предлагать перевод.

<span translate>page.login.btnsubmit</span>

отлично работает как текствнутренние теги переводятся.

Для перевода атрибута заполнителя

Ниже работает

<input type="text" translate="placeholder" placeholder="newworld">

Ниже не работает

<input type="text" matInput placeholder="Username / Email / Mobile" value="" translate="placeholder">

Это из-за входного атрибута matInput, который не принимает обновленное значение.

Какие возможности я мог бы обновить атрибуты matInput.I ловушка действия, которую я использую для директивы ngAfterViewInit

Спасибо.

РЕДАКТИРОВАТЬ 1 - ПЕРЕВОД ДИРЕКТИВ TS

import { Directive, ElementRef, Input } from '@angular/core';
import * as _ from 'lodash';
import { TranslateService } from '../services/translate.service';

@Directive({
  selector: '[translate]'
})
export class TranslateDirective {

  @Input('translate') referrer:string;

  constructor(private el: ElementRef, private ts: TranslateService) {

  }

  ngAfterViewInit() {
    if(_.isEmpty(this.referrer)){ // executed for text between the tags example: <span translate>page.login.username</span>
      this.translateInnerHtml()
    }else{ // executed for attributes
      this.translateAttribute();
    }
    return;
  }

  translateAttribute(){ // Not updating
    this.el.nativeElement.attributes.placeholder.value="dynamic placeholder";
  }

  translateInnerHtml(){ // Working fine as expected
    const innerHtml = this.el.nativeElement.innerHTML;
    if (_.isEmpty(innerHtml)) {
      this.el.nativeElement.innerHTML = 'No text provided for translation';
      return;
    }
    this.getTranslationText(innerHtml)
  }


  getTranslationText(text){
    let splitText = _.split(text, '.');
    let key = _.join(splitText.slice(-1));
    let file = _.join(splitText.slice(-2, -1));
    let folder = _.join(splitText.slice(0, splitText.length - 2), '/');
    if (_.isEmpty(key) || _.isEmpty(file) || _.isEmpty(folder)) {
      this.el.nativeElement.innerHTML = 'No text provided for translation';
      return;
    }
    this.ts.get(folder, file).subscribe(
      (data) => {
        if (_.isEmpty(data) || _.isEmpty(data[key])) {
          this.el.nativeElement.innerHTML = 'No text provided for translation';
          return;
        }
        this.el.nativeElement.innerHTML = data[key];
      }
    )
  }

}

Добавление стекаблиц-кода

Ответы [ 3 ]

0 голосов
/ 22 октября 2018

Чтобы изменить заполнитель в matInput, используйте mat-placeHolder, например

<mat-form-field class="username">
     <input type="text" matInput [(ngModel)]="user.username" >
     <mat-placeholder>
        <span translate>page.login.btnsubmit</span>
     </mat-placeholder>
</mat-form-field>
0 голосов
/ 10 августа 2019

В моем случае помогло только что-то подобное:

ngAfterViewChecked(): void {
    this.setPlaceHolder();
  }
0 голосов
/ 20 октября 2018

Issue

Прежде всего, ваш код работает нормально и устанавливает поле placeholder из input.На экране вы видите div placeholder, созданный директивой matInput.

Fix

Всякий раз, когда выдается директива matInput, нам нужно изменить placeholderattribute из MatInput, чтобы изменить placeholder `div.

Выполните шаги, чтобы изменить свойство placeholder MatInput

1.Установите ссылку matInput как #matInput="matInput"

Установите ссылку matInput в html, чтобы к ней можно было обращаться в translate directive.

 <input type="text" matInput #matInput="matInput" placeholder="Original 
     Placeholder" [(ngModel)]="user.username" translate="placeholder"> 

2.Измените модель placeholder из matInput.

Откройте директиву matInput в директиве translate

 @ContentChild("matInput") matInput : MatInput;

Измените заполнитель matInput

this.matInput.placeholder = "Translated placeholder";

Рабочая копия здесь https://stackblitz.com/edit/angular-q1ufxj

...