2017-04-24 1 views
0

사용자가 다양한 서비스에 가입하는 환경 설정 화면이 있습니다.이 서비스는 서비스에서 수신됩니다.각도로 동적 형태 제어

내 JSON은

[ { 
     category : 'General', 
     source : [ { name: 'ABC News', url: 'abc-news-au', subscribed: false}, 
         { name: 'Associated Press', url: 'associated-press', subscribed: false}], 
     numberofarticles: 4 
    }, 
repeat above node multiple times 
] 

그래서 서비스가 X에게 사용자를 구독 할 수 있습니다 서로 다른 범주를 보낼 수 있습니다 이런 종류의 무언가이다. 그리고 각 카테고리에서 그는 구독하고 싶은 뉴스 채널을 선택할 수 있습니다.

환경 설정 화면을 빌드 중이며 여기에 나열된 모든 항목이 업데이트/저장을 위해 서버에 전송되는 동적 UI를 만드는 방법에 조금 얽혀 있습니다.

템플릿 기반 접근 방식을 사용하면 양식을 쉽게 만들 수 있지만 값을 돌려 보내는 것은 효과가 없습니다.

니스

을 가지고 - 나는 각 사용자가 한 클릭하고 JSON을 업데이트 확인 수동으로 해달라고 그래서 또한 내가 어떤 업데이트가 사용자가 직접 JSON에 저장됩니다 않는 방법을 찾기 위해 노력하고있다. 예 : 사용자가 'ABC 뉴스'채널을 선택하면 구독 옵션이 True가됩니다.

템플릿 양식

form (ngSubmit)="onSubmit(f)" #f="ngForm"> 
    <md-tab-group> 
    <md-tab *ngFor="let news of newsList" label={‌{news.category}}> 

     <h3 color="accent">Select news sources</h3> 
     <md-select multiple placeholder="" ngModel name="{‌{news.source}}"> 
      <md-option *ngFor="let source of news.source" [value]="source.name"> 
      {‌{source.name}} 
     </md-option> 
     </md-select> 
     <br> 

     <h3>Number of new articles of each topic</h3> 
     <md-slider ngModel #numberofArticles name="numberofArticles" min="1" max="5" step="1" 
     value={‌{news.NoOfArticles}} tickInterval="auto" thumbLabel></md-slider> 
     <br> 

    </md-tab> 
    </md-tab-group> 
<br> 
<button md-raised-button color="primary" type="submit" >Save</button> 
</form> 

감사

답변

0

당신은 아마 당신이 TS 동적에서 구축 할 수있는 대신 FormsModule의 ReactiveFormsModule을 사용해야합니다. REACTIVE FORMS

+0

나는 https://toddmotto.com/angular-dynamic-components-forms#creating-a-dynamic [링크] (이 작업을 수행 할 수있는 방법에 토드의 기사를 통해 읽었다 -form) 그러나 나는 재료 디자인을 사용하고 싶었다. 위의 시나리오에서 Reactive Forms + Material 디자인을 사용하는 가장 좋은 방법은 무엇인지 알아야합니다. – happy

0

템플릿 기반 양식으로 처리 할 수 ​​있었지만 반응 형 양식은 내 시나리오에 적합하지 않았습니다. 있는 HTML이 더 많거나 적은 같은 나는 고유 한 이름

템플릿 양식

<form (ngSubmit)="onSubmit(f)" #f="ngForm"> 

<md-tab-group> 
    <md-tab *ngFor="let news of newsList; let i=index" 
      label={{news.category}} 
      ngModelGroup={{news.category}} 
      #{{news.category}}="ngModelGroup" 
      > 
     <h3 color="accent">Select news sources</h3> 
     <br> 
     <section class="example-section" ngModelGroup="news"> 
       <md-checkbox ngModel class="example-margin" 
          name={{news.category}}_{{x}} 
          *ngFor="let source of news.source; let x=index" 
          [(ngModel)]="source.subscribed"> 
        {{source.name}} 
       </md-checkbox> 
      </section> 

     <h3>Number of new articles of each topic</h3> 
     <md-slider ngModel name="numberofArticles_{{i}}" 
        min="1" max="5" step="1" 
        value={{news.NoOfArticles}} tickInterval="auto" 
        thumbLabel> 
     </md-slider> 
     <br> 
    </md-tab> 
    </md-tab-group> 
    <br> 
    <button md-raised-button color="primary" type="submit" >Save</button> 
</form> 

로를 가지고 인덱스를 추가 제외입니다

{사람이 반응 형태의 방법을 찾을 경우 알려 않습니다} 이 루프를 통해 반복되는 각 범주에는 해당 노드의 고유 한 이름이 있습니다. 또한 ngModelGroup을 사용하여 요소를 그룹화하면 나중에 많은 도움이되었습니다.

구성 요소 코드

onSubmit(f: NgForm) { 
    // Check if form is dirty 
     if (f.dirty) { 
      const myControls = f.controls; 
      let i = 0; 
      // Update the user preferences based on what he selected on the ui. DefaultNews is my model data which is needs to be updated 
      const defaultCategories = DefaultNews.defaultNews; 

      defaultCategories.forEach(element => { 
       // Check if the news category is dirty - i.e. each Tab on the UI 
       if ((myControls[element.category]).dirty) { 
        // check if news websites were touched i.e. if any checkbox from the group is updated 
        if ((myControls[element.category].get('news')).dirty) { 
         let newsSubscription; 
         let index = 0; 
         // Read thru each news source and set it from the ui 
         element.source.forEach(newsSource => { 
          newsSubscription = (myControls[element.category].get('news')).get(element.category + '_' + index); 
          newsSource.subscribed = newsSubscription.value; 
          index = index + 1; 
         }); 
        } 
        // check if the number of articles was touched - i.e. if slider was moved 
        if ((myControls[element.category].get('numberofArticles_' + i)).dirty) { 
        element.NoOfArticles = (myControls[element.category].get('numberofArticles_' + i)).value; 
        } 

        i = i + 1; 
       } 
      }); 
     } 
    } 

나는 예 다음 예에만 다음 가서 업데이트 사용자 선호도 경우 특정 노드가 더러 확인하면 양식이 더러운 경우 확인.

환경 설정 화면이 무엇인지 알기 위해 스크린 샷을 첨부했습니다. 필자는 실제 코드를 더 쉽게 이해할 수 있도록 요소 및 스타일 제고 측면에서 단순하게 유지했습니다.

First Tab of Preferences screen

Second Tab of Preferences screen