Как проверить переключатель на основе ngModel, с которым он связан - PullRequest
0 голосов
/ 14 февраля 2019

Я пишу простую Angular 7 страницу, которая содержит 2 переключателя и один ввод текста.Когда страница загружается, метод ngOnInit выполняет вызов базы данных и извлекает некоторые данные, которые должны быть отражены в переключателях и вводе текста.Я не могу сделать так, чтобы переключатели были выбраны при открытии страницы на основе значения, полученного из базы данных.

app.component.html

<label>Descrição adicional</label>
<br />
<input type="text" [(ngModel)]="metadata.dscStatusSul" />
<!--this input text simply shows the value stored in the database column "dscStatusSul" which is a string-->
<br />
<label>Código do funcionamento</label>
<br /><input type="text" [(ngModel)]="metadata.numStatusSul" />
<!--this input text simply shows the value stored in the database column "numStatusSul" which is a number varying between 1 and 0 -->
<div class="col-md-4">
    <label>
        <input [(ngModel)]="metadata.numStatusSul" type="radio" name="rdoResult" value="0" />
        <!--this radio button should be checked when the page loads when the value retrieved from the database is 0 -->
        Operação Normal
    </label>
    <label>
        <input [(ngModel)]="metadata.numStatusSul" type="radio" name="rdoResult" value="1" />
        <!--this radio button should be checked when the page loads when the value retrieved from the database is 1 -->
        Operação Intermitente
    </label>
</div>
<br />
<button (click)="salvarDados()">Salvar</button>
<!-- this a button that sends a request to the database to update the data that was retrieved-->

app.component.ts

import { Component, OnInit } from '@angular/core';
import { AppApi } from './app-api';
import Metadata from './Metadata';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AppApi]
})
export class AppComponent implements OnInit {

  private metadata: Metadata;


  constructor(private appApi: AppApi) {
    this.metadata = new Metadata('', '', '', '', '', '', 0, 0, 0, 0, 0, 0); //this creates a new empty blank object to store the retrieved data
  }

  ngOnInit() {
    this.pegarDados(); //this line calls the method that gets the initial data from the database
  }

  pegarDados() { //this method makes a request to the database and then saves the data to the "metadata" object.
    this.appApi.getConfig().toPromise()
      .then((res) => {
        console.log('Pegou os dados');
        this.metadata = res[0];
      })
      .catch((err) => {
        console.log('Erro:');
        console.log(err);
      });
  }

  salvarDados() {//This method is supposed to make a request to the database and update the existing data with the data that was changed in the HTML page.

    console.log('Teste Salvar Dados');
    //curently it only displays the new data in the console. The data being shown here is compatible with what is selected in the HTML page.
    console.log(this.metadata.dscStatusSul);
    console.log(this.metadata.numStatusSul);

    /*this.appApi.setConfig(this.metadata).toPromise()
      .then((res) => {
        console.log('Chegou aqui');
        this.metadata = res[0];
        console.log(this.metadata);
      })
      .catch((err) => {
        console.log('Erro:');
        console.log(err);

      });*/
  }
}

По сути, единственная проблема заключается в том, что я не могу проверить соответствующую кнопку-переключатель, когда страница загружается на основе того, что извлекается из базы данных функцией "pegarDados ()".

1 Ответ

0 голосов
/ 14 февраля 2019

Когда вы устанавливаете значение переключателя с помощью value="0", вы устанавливаете его как строку "0", которая не соответствует числовому значению, привязанному к полю ввода.Чтобы установить значение переключателя в виде числа, используйте скобки: [value]="0".

<input [(ngModel)]="metadata.numStatusSul" type="radio" name="rdoResult" [value]="0" />
<input [(ngModel)]="metadata.numStatusSul" type="radio" name="rdoResult" [value]="1" />

См. этот стек в качестве демонстрационной версии.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...