#angular #angular-template
#angular #angular-template
Вопрос:
У меня есть форма, которая должна отображать 2 поля, если установлен флажок «Продажи». Когда пользователь нажимает на него вручную, все идет хорошо.
Но у меня также есть кнопка, которая устанавливает этот флажок. Когда это происходит, 2 поля не отображаются, если пользователь вручную повторно не установит флажок.
Вы можете увидеть снимок экрана здесь: https://gfycat.com/WellmadeCapitalAdouri
child.html
<div *ngIf="userTemplates != null amp;amp; roles != null amp;amp; departments != null">
<fieldset class="blue">
<legend>Profiles SugarCRM</legend>
<button (click)="handleClick($event, 'conseiller')">Ventes - Conseiller</button>
<button (click)="handleClick($event, 'jm')">Ventes – Junior Manager</button>
<button (click)="handleClick($event, 'manager')">Ventes - Manager</button>
<button (click)="handleClick($event, 'assistant')">Ventes – Assistant de ventes</button>
<button (click)="handleClick($event, 'qualite')">Agent Qualité</button>
<button (click)="handleClick($event, 'compta')">Compta</button>
<button (click)="handleClick($event, 'inactif')">Inactif</button>
<div class="select subtitle">Hérite les préférence de l'utilisateur
<select name="userToCopyHPfrom" [(ngModel)]="userValue">
<option *ngFor="let user of userTemplates ; trackBy: trackByFn" [value]="user.value">
{{ user.label | uppercase }}
</option>
</select>
</div>
<div class="checkbox-list subtitle" id="sugar_role" ngModelGroup="roles">ROLE:
<span *ngFor="let role of roles; trackBy: trackByFn">
<label><input type="checkbox" [(ngModel)]="role.checked" [name]="role.id">{{ role.name }}
</label>
</span>
</div>
<div class="checkbox-list subtitle" id="sugar_departement" ngModelGroup="departments">DEPARTMENT:
<span *ngFor="let department of departments ; trackBy: trackByFn">
<label>
<input [id]="department.id" type="checkbox" [name]="department.id" [ngModel]="department.checked" (ngModelChange)="onDepartmentChecked(department, $event)">{{ department.name }}
</label>
</span>
</div>
<div [hidden]="hideLeads">
<label>Leads min
<input
type="number"
name="leadsMin"
[(ngModel)]="currentUser.leadsMin">
</label>
</div>
<div [hidden]="hideLeads">
<label>Leads max
<input
type="number"
name="leadsMax"
[(ngModel)]="currentUser.leadsMax">
</label>
</div>
</fieldset>
</div>
component.ts
@Component({
selector: "mv-profiles",
templateUrl: "./profiles.component.html",
viewProviders: [
{
provide: ControlContainer,
useExisting: NgForm,
},
],
})
export class ProfilesComponent implements OnInit {
constructor(private http: HttpClient) {
//
}
public handleClick(e, type) {
const departments = this.departments;
const others = this.others;
const orgas = this.orgas;
this.resetSugar();
switch (type) {
case "conseiller":
{
this.userValue = "user_default";
this.checkRoles(["Sales"]);
this.checkStuff(departments, ["Ventes"]);
this.checkStuff(others, ["Global", "Ventes", "Devis Cotation", "ROLE - Reservation"]);
break;
}
case "jm":
{
this.userValue = "user_default_jm";
this.selectedFunction = "jm";
this.checkRoles(["Sales"]);
this.checkStuff(departments, ["Ventes"]);
this.checkStuff(others,
[
"Global",
"Ventes",
"Devis Cotation",
"ROLE - BI Validation",
"ROLE - ViewRCM",
"ROLE - View RM",
"Ventes",
],
);
break;
}
case "manager":
{
this.selectedFunction = "mgr";
this.checkRoles(["Team Manager"]);
this.checkStuff(departments, ["Ventes"]);
this.checkStuff(others, [
"Global",
"Devis Cotation", "Devis V3",
"ROLE - BI Validation",
"Ventes",
],
);
break;
}
case "assistant":
{
this.selectedFunction = "av";
this.checkRoles(["Reservation"]);
this.checkStuff(departments, ["Ventes"]);
this.checkStuff(others, [
"Devis V3",
"Devis Cotation",
"Global",
"Reservation",
"ROLE - Reservation",
]);
break;
}
case "qualite":
{
this.selectedFunction = "aq";
this.selectedOffice = "Bureau - Billetterie amp; Qualité";
this.selectedManager = "Manager du service qualité (Aminata)";
this.checkRoles(["Quality Control"]);
this.checkStuff(departments, ["Service Qualité"]);
this.checkStuff(others, ["BackOffice", "Global", "SAV"]);
this.checkStuff(orgas, ["BackOffice"]);
break;
}
case "compta":
{
this.selectedOffice = "1377";
this.checkRoles(["Accountant"]);
this.checkStuff(departments, ["Comptabilité"]);
this.checkStuff(others, ["Global", "ROLE - Affaire Validation", "ROLE - Create Provider"]);
this.checkStuff(orgas, ["Compta"]);
break;
}
case "inactif":
{
this.checkRoles(["ReadOnly"]);
this.inactiveStatus = true;
this.inactiveEmployee = true;
break;
}
default:
// code...
break;
}
}
public onDepartmentChecked(department, e) {
if (department.id === "departments-Ventes") {
this.hideLeads = !e;
}
}
public checkStuff(where, arr) {
let prefix;
switch (where) {
case this.orgas:
prefix = "orgas";
break;
case this.departments:
prefix = "departments";
break;
case this.others:
prefix = "others";
break;
default:
console.error("Wrong input");
break;
}
arr.forEach((element) => {
const myOther = where.find((other) => other.id === `${prefix}-${element}`);
if (!!myOther) { myOther.checked = true; }
});
}
public eraseFields(fields) {
fields.forEach((field) => field = "");
}
public unCheck(array) {
array.forEach((x) => x.checked = false);
}
public trackByFn(index, item) {
const self = this;
return item.id; // or index
}
private unCheckArrays(arrays) {
arrays.forEach((array) => this.unCheck(array));
}
private resetSugar() {
this.inactiveStatus = false,
this.inactiveEmployee = false,
this.currentUser.leadsMin = 15;
this.currentUser.leadsMax = 45;
this.userValue = "user_default_xx";
this.selectedManager = null,
this.eraseFields([
this.codeSON,
this.codeTourplan,
this.codevad,
this.groupes,
this.inbound,
this.outbound,
this.phoneExtension,
this.phoneNumber,
this.selectedOffice,
this.selectedFunction,
this.selectedOrganisation,
this.title,
]);
this.unCheckArrays([
this.roles,
this.departments,
this.others,
this.teams,
this.destinations,
this.orgas,
]);
}
private checkRoles(rolesToCheck) {
rolesToCheck.forEach((roleToCheck) => {
this.roles.find((role) => role.name === roleToCheck).checked = true;
});
}
Я попытался добавить
this.cd.detectChanges();
и запуск функции внутри зоны
this.zone.run(() => {...});
но ни одно из этих решений ничего не изменило
Комментарии:
1. ‘Но у меня также есть кнопка, которая устанавливает этот флажок’ можете ли вы также включить этот код.
2. Я только что добавил больше кода — надеюсь, он не слишком подробный. Как вы, возможно, уже догадались, я младший 🙂 @Senal
3. Вызываете ли вы ту же логику
handleClick
, когда нажимаете кнопку?detechChanges
скорее не должно быть необходимо, поскольку оно в любом случае запускается в ответ на нажатие кнопки.4. Вы не изменяете
hideLeads
на своемcheckStuff
, поэтому он никогда не сможет отображаться. Вы должны каким-то образом вызвать функциюonDepartmentChecked
inhandleClick
, чтобы и нажатие флажка, и нажатие кнопки выполняли одинаковую функциональность. Переместите всю логику вonDepartmentChecked
и просто вызовите этот метод для каждого флажка, с которым связана кнопка вhandleClick
.5. можете ли вы создать stackblitz для этого сценария?
Ответ №1:
Когда пользователь вручную устанавливает флажок, он вызывает метод onDepartmentChecked(), но когда и в этом методе вы устанавливаете hideleads в true или false, но когда вы проверяете, что chebox использует другой метод, вы не вызываете этот метод. в этом проблема.
public onDepartmentChecked(department, e) {
if (department.id === "departments-Ventes") {
this.hideLeads = !e;
}
}