【问题标题】:Get value with ngModel in ion-toggle在 ion-toggle 中使用 ngModel 获取价值
【发布时间】:2022-01-25 17:55:40
【问题描述】:

我想根据 db 表上存在的值设置一个 ion-toggle。

如果值存储在表中,则切换应为 ON,如果不是 OFF。关(左)开(右)

所以,如果 Artist_interests 表中的艺术家列有 Cinematographer 的值,那么我想要 开启

这是我目前所拥有的。

html

    <ion-item>
      <ion-label>Cinematographers</ion-label>
      <ion-toggle color="success" [(ngModel)]="artistInterests.Cinematographers" (click)="artistInterest(artists, 'Cinematographers')"></ion-toggle>
    </ion-item>

    <ion-item>
      <ion-label>Graphic Designers</ion-label>
      <ion-toggle color="gold-white" [(ngModel)]="artistInterests.graphicDesigners" (click)="artistInterest(artists, 'Graphic Designers')"></ion-toggle>
    </ion-item>

.ts 调用 API 函数在 DB 表上存储值(例如图形设计师) - 我的意思是它将“图形设计师”存储在 DB 表的艺术家列中。

artistInterest(artists:string, messageTitle: string)
{
    this.userData.artistSettings(this.userDetails.uid, messageTitle).pipe(
      map((data: any) => {
        if (data.success) {
          Swal.fire({
            icon: 'success',
            title: messageTitle,
            showConfirmButton: false,
            backdrop: false,
            timer: 2500
          })
        }
      })
    ).subscribe()
  }

.ts 函数从 api 函数中检索数据

export class CreativeSettingsPage implements OnInit {
  creativeInterests: any= {};
  creative: any= {};
  artistInterests: any= {};
  artists: any= {};
  userDetails: any = {};
  constructor(
    public userData: UserData
  ) {
    this.userDetails = this.userData.getUserData();
    this.creativeInsterestSet();
    this.artistsInsterestSet;
   }

ngOnInit() {
    this.artistsInsterestSet()
  }

artistsInsterestSet() {
this.userData.artistsInterests(this.userDetails.uid).pipe(
      map((data: any) => {
          if (data.success) {
              this.artistInterests = data.artistInterests;
              console.log( this.artistInterests);
          }
      })
  ).subscribe()
}

userData.ts

  artistsInterests(uid:number) {
    const url = this.appData.getApiUrl() + 'getArtistInterests';
    const data = this.jsonToURLEncoded({
        uid: uid
    });
    return this.http.post(url, data, { headers: this.options });
}

php函数getArtistInterests

function getArtistInterests()
{
    $request = \Slim\Slim::getInstance()->request();
    $data = json_decode($request->getBody());
    $response['success'] = true; // 1

     $uid = $request->post('uid');

    $db = getDB();
    $sql = "SELECT A.artist, U.profile_pic,U.first_name,U.last_name,
    DATE_FORMAT(A.created, '%W %D %M %Y, %l %i %p') as date
    FROM  artists_interests A 
    LEFT JOIN users U ON A.uid_fk=U.uid 
    WHERE A.uid_fk=? GROUP BY A.artist";
    $stmt = $db->prepare($sql);
    $stmt->execute(array($uid));

    $db = null;
    $artistInterests = $stmt->fetchAll(PDO::FETCH_OBJ);

    foreach ($artistInterests as $feed) {
        $feed->profile_pic = SITE_URL . 'usersPic/' . $feed->profile_pic;
    }

    $data['success'] = true;
    $data['artistInterests'] = $artistInterests;
    echo json_encode($data);
}

值存储为例如Artist_interests 表中的平面设计师(两个词),因此 [(ngModel)]="artistInterests.graphicDesigners" 将不起作用。但据我所知,它应该适用于 [(ngModel)]="artistInterests.Cinematographers"。通过工作,我的意思是打开工具(就在幻灯片上)

【问题讨论】:

  • 使用checked 属性。例如:&lt;ion-toggle color="success" [(ngModel)]="artistInterests.Cinematographers" checked="artistInterests.Cinematographers ? true : false" (ionChange)="artistInterest(artists, 'Cinematographers')"&gt;&lt;/ion-toggle&gt; .也为事件使用 ionchange
  • 如果您不使用 ngFor,您如何获得所有这些切换按钮?
  • 查看代码 Najam

标签: angular ionic-framework


【解决方案1】:

使用 ng-model 的 ion-toogle 只能获得两个值“true”或“false”(就像输入类型复选框)。如果您想将真/假“转换”为开/关,您可以使用类似

<ion-toogle [ngModel]="artistInterests.Cinematographers=='ON'?true:false"
            (ngModelChange)=artistInteres.Cinematographers=$event?'ON':'OFF'>

注意:如果您使用[(ngModel)](或在reactiveForms 中使用formControlName,请尝试避免使用[checked][value] 或其他属性。

注意 2:当我们使用 ion-toogle 或其他使用 [(ngModel)] 的组件(可以是材料中的组件或 ng-bootstrap 中的组件)时,可以在 .html 中使用 [(ngModel)]="value{{value|json}} 来了解真的返回什么值

更新我终于明白你的问题了。我想你有两张桌子:

artist_interest=[{uid_fk:..,artist:...,created:...}...]
//and
users=[{uid:..,profile_pic:...,first_name:...,last_name:...}]

在通话中你会得到一些喜欢

[{artist:"Painters",date:"Friday 21 January 2022,1 08 PM",firstName:"test",lastName:"User",uid:1122},
    {artist:"Graphic Designers",date:"Monday 24 January 2022,1 08 PM",firstName:"test",lastName:"User",uid:1122}]

您想显示数据,更改时删除“artist_interest”中的元素,然后添加“artist_interest”中的元素

此外,您还有一系列“目录”

你可以采取两种方法:

  1. 离子删除/添加到数据库的每次更改
  2. 拥有一个按钮并进行唯一调用以删除/添加新 元素

如果你采用第一种方法,你只需要一个函数来知道类别是否在数组中

  isInInterest(cathegory:string)
  {
    return this.artistInterests.find(x=>x.artist==cathegory)?true:false
  }

你有一些喜欢

  <ion-row *ngFor="let cathegory of cathegories;let i=index">
    <ion-item>
      <ion-label>{{cathegory}}</ion-label>
      <ion-toggle [ngModel]="isInInterest(cathegory)"
                  (ngModelChange)="change($event,cathegory)"
        color="success"
      ></ion-toggle>
    </ion-item>
  </ion-row>

你喜欢的地方

  change(checked:boolean,cathegory:string)
  {
    if (checked)
    { 
        this.service.add(cathegory).subscribe(res=>{
          this.artistInterests.push(res)
        })
    }
    else
    {
      this.service.remove(cathegory).subscribe(res=>{
        if (res.success==true)
        {
          this.artistInterests=this.artistInterests.filter(x=>x.artist!=cathegory)
        }
      })
    }
  }

看看如何,我们订阅了我们的服务“add”和“remove”的方法,然后我们需要手动添加/删除我们数组的元素。

对于第二种方法,我们使用了一个辅助对象数组,该数组使用“map”和分类列表创建。

在获得艺术家后 - 在订阅中我们创建我们的数组

this.cathegoriesValues=this.cathegories.map(x=>{
  const isInInterest=this.artistInterests.find(a=>a.artist==x)?true:false
  return {
    cathegory:x,oldValue:isInInterest,newValue:isInInterest}
})

我们使用一些类似

  <ion-row *ngFor="let cathegory of cathegoriesValues;let i=index">
    <ion-item>
      <ion-label>{{cathegory.cathegory}}</ion-label>
      <ion-toggle [(ngModel)]="cathegory.newValue" color="success"></ion-toggle>
    </ion-item>
  </ion-row>

只是,在按钮中,我们过滤 newValue 和 oldValue 不同的数据,并调用我们的服务来删除/添加数据到我们的 dbs

submit()
{
   const data=this.cathegoriesValues.filter(x=>x.newValue!=x.oldValue)
   this.serviceUpdateDbs(this.artistInterests.uii,data)
}

注意:我创建了一个小而不完整的 stackblitz here

【讨论】:

  • 不,我不想将其用作 ON 或 OFF。通过开或关,我的意思是如果数据库上存在该值,那么它就是正确的
  • 我的错,对不起!真的我不知道你的代码或者你是否有兴趣列表。前段时间我写了这个SO 来使用一系列复选框来管理一个数组。不知道能不能帮到你
  • 如果artistInterest 是Cinematographers 的值,我只希望切换开关位于右侧。什么使切换为真或假?
  • @PellaPost,我更新了我的旧答案,希望对你有帮助
猜你喜欢
  • 2017-04-05
  • 1970-01-01
  • 2016-04-27
  • 2016-07-04
  • 2017-02-07
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
相关资源
最近更新 更多