ngModel не обновляет значение - PullRequest
0 голосов
/ 28 марта 2019

Я довольно новичок в Angular. Я надеюсь, что кто-нибудь поможет мне понять, что я делаю неправильно.Я пытался понять это целую вечность.

Я использую pdftron внешний API, который дает вам возможность показать PDF, выбрать текст и отобразить его.Итак, я создал экземпляр pdftron и, как только выделю, прослушиваю добавленную аннотацию события, я получаю данные (выделенный текст).Теперь, как только люди выбирают текст, я хочу, чтобы он отображался в поле ввода, которое у меня есть, но я не могу этого сделать.Я отображаю все поля ввода с помощью итераций via ngfor.У меня есть модель, которая определяет, что происходит с формой.

Это моя модель формы:

export class FormModel {
  id: number;
  inputText: string;
  placeholder: string;
  required: boolean;
  firstCheck: boolean;
  secondCheck: boolean;
  value: any;
  metadata: any;
}

Это мой компонент формы:

<div class="row form_content">
  <div class="col-12">
    <form>
      <div
        *ngFor="let item of formelement"
        [class.selected]="item.id === selectedInput"
        class="form-group row"
      >
        <label for="{{ item.inputText }}" class="col-sm-4 col-form-label">{{
          item.inputText
        }}</label>
        <div class="col-sm-6">
          <i
            class="fas fa-exclamation-circle fa-lg mr-1"
            [hidden]="!item.required"
          ></i>
          <input
            type="text"
            class="form-control"
            id="{{ item.inputText }}"
            (click)="onfocus(item.id)"
            placeholder="{{ item.placeholder }}"
            [(ngModel)]="item.value"
            [ngModelOptions]="{ standalone: true }"
          />
        </div>
        <div
          class="col-1 check_circle first_check_circle col-1 d-flex justify-content-center align-items-center"
        >
          <i
            class="fas"
            [ngClass]="
              item.firstCheck
                ? 'fa-check-circle fa-check-circle-checked'
                : 'fa-check-circle'
            "
          ></i>
        </div>

        <div
          class="col-1 check_circle col-1 d-flex justify-content-center align-items-center"
        >
          <i
            class="fas fa-check-circle"
            [ngClass]="
              item.secondCheck
                ? 'fa-check-circle fa-check-circle-checked'
                : 'fa-check-circle'
            "
          ></i>
        </div>
      </div>
    </form>
  </div>
</div>

Это мой машинописный файл компонента.

import {
  Component,
  OnInit
} from '@angular/core';
import { FormModel } from './form.model';
import { PdfTronService } from 'src/app/components/home/pdftron/pdftron.service';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
  selectedInput: number;
  formelement: FormModel[] = [
    {
      id: 0,
      inputText: 'Increase Amount',
      placeholder: 'Increase Amount',
      required: true,
      firstCheck: true,
      secondCheck: false,
      value: '',
      metadata: ''
    },
    {
      id: 1,
      inputText: 'Increase Frequency',
      placeholder: 'Increase Frequency',
      required: true,
      firstCheck: false,
      secondCheck: true,
      value: '',
      metadata: ''
    }
  ];

  constructor(
    private pdftronService: PdfTronService
  ) {}

  ngOnInit() {}

  onfocus(id) {
    this.selectedInput = id;
    this.pdftronService.webViewerInstance.setToolMode(
      'AnnotationCreateTextHighlight'
    );
    this.pdftronService.annotManager.on(
      'annotationChanged',
      (event, annotations, action) => {
        if (action === 'add') {
          // this should update the input value and show on UI but it does not until i click the other input field. 
          this.formelement[
            this.selectedInput
          ].value = annotations[0].getContents();
          // code reaches all the way to the end
          console.log('Running from here');
        }
      }
    );
  }
}

Как вы можете видеть, когда кто-то нажимает на поле ввода.Я вызываю onfocus и настраиваю инструмент pdftron, чтобы выделить и прослушать прослушиватель событий на annotationchanged.Как только они добавляют аннотацию выделения, я получаю текст с использованием annotation.getContents и обновляю значение для ввода.Но это не меняет значения во входных данных автоматически, равно как и когда я щелкаю за пределами поля ввода.Он обновляется только тогда, когда я щелкаю другое поле ввода в моей форме.

Но я не хочу, чтобы вместо этого я хотел, чтобы он обновлялся, как только кто-то перестал выбирать текст. Я не знаю, что я делаю неправильно, и пытался выяснить это в течение последних 2 недель.,Я надеюсь, что вопрос имеет смысл.Я хотел бы уточнить это дальше.Любая помощь будет высоко ценится.

Спасибо.

1 Ответ

0 голосов
/ 29 марта 2019

Я не знаю, правильно ли это делать, но я смог решить ее, используя ChangeDetectorRef. Я вызвал метод detectChanges, как только я обновил значение. Несмотря на то, что я решил это, я не знаю, правильно ли это сделать. Вот как выглядит мой набор текста, и он обновляет значение, как только люди выбирают текст.

import {
  Component,
  OnInit,
  ChangeDetectorRef
} from '@angular/core';
import { FormModel } from './form.model';
import { requiredDataService } from './form.service';
import { PdfTronService } from 'src/app/components/home/pdftron/pdftron.service';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
  selectedInput: number;
  formelement: FormModel[] = [
    {
      id: 0,
      inputText: 'Increase Amount',
      placeholder: 'Increase Amount',
      required: true,
      firstCheck: true,
      secondCheck: false,
      value: '',
      metadata: ''
    },
    {
      id: 1,
      inputText: 'Increase Frequency',
      placeholder: 'Increase Frequency',
      required: true,
      firstCheck: false,
      secondCheck: true,
      value: '',
      metadata: ''
    }
  ];

  constructor(
    private requiredData: requiredDataService,
    private pdftronService: PdfTronService,
    private changeRef: ChangeDetectorRef
  ) {}

  ngOnInit() {}

  onfocus(id) {
    this.selectedInput = id;
    this.pdftronService.webViewerInstance.setToolMode(
      'AnnotationCreateTextHighlight'
    );
    this.pdftronService.annotManager.on(
      'annotationChanged',
      (event, annotations, action) => {
        if (action === 'add') {
          // this should update the input value and show but it does not unless i click the other input field
          this.formelement[
            this.selectedInput
          ].value = annotations[0].getContents();
          // Detecting the change in application state. 
          this.changeRef.detectChanges();
          // code reaches all the way to the end
          console.log('Running from here');
        }
      }
    );
  }
}
...