修改输入值并集中输入字段后防止自动提交

时间:2019-01-25 23:08:49

标签: angular typescript angular6

我实施了搜索表格。我希望看到的是,就像普通的搜索表单一样,在完成第一次搜索之后,如果我更改输入值并输入或单击“提交”按钮,则会看到新结果。但是,如果我更改输入值并在不点击Enter或单击Submit按钮的情况下将焦点放在输入字段上,则会发生自动提交。

我想我想知道为什么会这样,输入标签中的(click)=“ backToDefault()”函数,但是我不知道如何解决。

这是HTML格式

<div id = "start">
<form id = "searchform" [formGroup]="form" (ngSubmit)="onSubmit()">
    <div id = "searchbox">
        <input id = "search" formControlName="summonerName" (change) = "backToDefault()" autocomplete="off" placeholder=" Summoner Name..  ex)dragonsoup2" required/>  
        <button id = "submit" type="submit">Search</button>
        <div id = "err1" class="alert alert-danger" *ngIf = "summonerName.invalid">Cannot be empty</div>
        <div id = "err2" class="alert alert-danger" *ngIf = "summonerName.valid"></div>
    </div>
    <app-summoner-history *ngIf = "submitted && checkObj(heroes)" [userinfo] = "heroes"></app-summoner-history>
</form>

这是召唤师组件。

    import { Component, OnInit, Input, NgZone } from '@angular/core';
import { LOLUserData } from './lolinterface';
import { SummonerService } from './summoner.service';
import {FormControl, FormGroup, Validators} from '@angular/forms';

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

  private typed : boolean = false;
  private heroes: LOLUserData;
  private url: string = 'http://ddragon.leagueoflegends.com/cdn/9.2.1/img/profileicon/';
  private profileimg: string = "";
  private notMatching: boolean = false;
  private errorMsg: string = "";
  public form: FormGroup;
  public summonerName: FormControl;
  private fromClick : boolean = false;
  private submitted: boolean = false;
  private wrong: boolean = false;
  constructor(private summonerService: SummonerService, private zone: NgZone) {  }

  ngOnInit(): void {
    this.summonerName = new FormControl('', Validators.required)
    this.form = new FormGroup({
      summonerName: this.summonerName
    });
  }

  getHeroes(name: string): void {
    this.summonerService.getdata(name)
    .subscribe(hero => {
        this.heroes = hero;
        this.heroes.profileimg = this.url + this.heroes.profileIconId + ".png";
        this.heroes.searchForm = this.form;
        this.heroes.searchControl = this.summonerName;
        this.submitted = true;
          this.summonerService.getRankdata(this.heroes.id)
          .subscribe(rank => {
              this.heroes.rank = rank;
            });
        },       
        (error => this.setErrValue(this.heroes))
      );
  }
  setErrValue(ob: any){
    this.submitted = false;
    if(ob == null){
      let err2 = document.getElementById("err2");
      err2.style.display = "block";
      err2.innerHTML = "Cannot find the Summoner";
    }
  }
  inputValidate(invalid: boolean){
    if(invalid){
      let err1 = document.getElementById("err1");
      if(err1 != null || err1.style.display == "none"){
        console.log("here");
        err1.style.display = "block";
      }
      this.submitted = false;
      return false;
    }
    else{
      return true;
    }
  }
  onSubmit(){
      if(!this.inputValidate(this.form.invalid))
        return;
      this.getHeroes(this.form.get("summonerName").value);
  }

  backToDefault(){
        this.heroes = null;
  }

  checkObj(hrs: LOLUserData) : boolean{
    let input = document.getElementById("search");
    let start = document.getElementById("start");
    let error1 = document.getElementById("err1");
    let error2 = document.getElementById("err2");
    let logo = document.getElementById("textLogo");
    let html = document.getElementsByTagName("html")[0];

    if(hrs != null){
      //console.log("came in = " + this.submitted);
      this.form.get("summonerName").markAsPristine();
      this.form.get("summonerName").markAsUntouched();

      html.style.backgroundImage = "linear-gradient(to bottom, transparent 60%, #07131A), url('../../assets/Bilgewater.jpg')";
      html.style.backgroundColor = "#07131A";
      html.style.backgroundSize = "100% 100%";
      html.style.backgroundRepeat = "no-repeat";

      input.style.marginTop = "0";

      logo.style.display = "none";

      start.style.marginTop = "0";
      start.style.paddingTop = "0";
      start.style.border = "none";
      start.style.borderRadius = "0";
      //start.style.borderBottom = "2px solid #D4D9FF";
      //start.style.boxShadow = "0 1px #9AA2E3";

      if( /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
        start.style.height= "60px"
      }
      else{
        start.style.height= "90px"
      }

      if(error1 != null){
        error1.style.display="none";
      }
      if(error2 != null){
        error2.style.display="none";
      }
      return true;
    }
    return false;
  }
}

如果有有效的get响应,它将转到Summoner History组件。ts

    export class SummonerHistoryComponent implements OnInit{

    @Input('userinfo') private info: LOLUserData;

  constructor(private summonerComponent: SummonerComponent, private summonerHistoryService: SummonerHistoryService, private summonerOneGameHistoryService: SummonerOnegameHistoryService) {}

  ngOnInit(){
    if(this.info != null){
        if(this.info.rank != undefined){
            this.rankinfo = this.info.rank.tier + " " + this.info.rank.rank + " / " + 
            this.info.rank.leaguePoints + " Point  / " + this.info.rank.wins + "W:" + this.info.rank.losses + "L";
        }
        else{
            this.rankinfo = "Unranked";
        }
        this.findHistory();
    }
  } 
  findHistory(){
        this.getHistory(this.info.accountId.toString());
    }
  getHistory(id: string): void {
    this.summonerHistoryService.getitem().subscribe((im) =>{
        this.item = im;
    });
    this.summonerHistoryService.getspell().subscribe((spl) =>{
        this.spell = spl;
    });
    this.summonerHistoryService.getdata(id)
    .subscribe((his) => {
        this.history = his;
        this.summonerHistoryService.getimage()
        .subscribe(img => 
        {
            this.champimages = img;
            for(let c of Object.values(this.champimages.data))
            {
                let mix : Array<any> = [];
                mix.push(c.image.full);
                mix.push(c.name);
                this.keys.set(c.key, mix);
            }
            this.history.champlist = this.keys;
            this.history.matches.forEach(ig => {
                let i: any[] = [];
                let mix = this.keys.get((ig.champion).toString());
                let champinfo = this.url + mix[0];
                i.push(champinfo);
                i.push(mix[1]);
                i.push(ig.gameId);
                this.images.push(i);            
            }); 
            this.summonerOneGameHistoryService.getdata(this.history)
            .subscribe((play) => {
                this.players = play;
                this.players.forEach(player => {
                    let winner: number;
                    let accinfo: Array<any[]> = [];
                    let temp: Array<any[]> = [];
                    let me: any[] = [];
                    let account: string[] = [];

                    let currdate = new Date();
                    let timetaken: number = player.gameDuration;
                    let gameCreated: number = player.gameCreation;
                    let gc = new Date(gameCreated);

                    //checking a date differenced between game creation and current date
                    let dayDifference: number = 
                    this.datediff(this.parseDate(currdate.getMonth(), currdate.getDay(), currdate.getFullYear()),
                                  this.parseDate(gc.getMonth(), gc.getDay(), gc.getFullYear()));

                //checking every game that has been played within 6 months.
                //if a game is older than 6 months, it will be discarded
                if(dayDifference < 185)
                {            
                    player.teams.forEach(winteam=>{
                        if(winteam.win == "Win")
                        {
                            winner = winteam.teamId;
                        }
                    })
                    player.participantIdentities.forEach(first=>{
                        let account: any[] = [];
                        account.push(first.player.summonerName);
                        account.push(first.player.accountId);
                        accinfo.push(account);
                    })
                    player.participants.forEach((igs, index) => {
                        //for each player's champ, spells, items, kda, total money earned, total minions killed
                        let acid = accinfo[index];
                        let temp2: any[] = [];
                        let kda: string = "";
                        let iturl: string[] = [];
                        let mix = this.history.champlist.get((igs.championId).toString());
                        let champinfo = this.url + mix[0];

                        //Champion image
                        temp2.push(champinfo);

                        //spells
                        temp2.push(this.findspell(igs.spell1Id));
                        temp2.push(this.findspell(igs.spell2Id));

                        //items
                        temp2.push(this.finditem(igs.stats.item0, temp2[0]));
                        temp2.push(this.finditem(igs.stats.item1, temp2[0]));
                        temp2.push(this.finditem(igs.stats.item2, temp2[0]));
                        temp2.push(this.finditem(igs.stats.item3, temp2[0]));
                        temp2.push(this.finditem(igs.stats.item4, temp2[0]));
                        temp2.push(this.finditem(igs.stats.item5, temp2[0]));
                        temp2.push(this.finditem(igs.stats.item6, temp2[0]));

                        //kda (Kill/Death/Assist)
                        kda = igs.stats.kills.toString() + "/" + igs.stats.deaths.toString() + "/" 
                        + igs.stats.assists.toString();
                        temp2.push(kda);
                        if(igs.stats.deaths == 0){//when there is no death
                            temp2.push("PERFECT KDA");
                        }else{
                            temp2.push(((igs.stats.kills + igs.stats.assists) / igs.stats.deaths).toFixed(2) + ":1 KDA");
                        }

                        //minions
                        temp2.push(igs.stats.totalMinionsKilled + " CS");
                        //money earned
                        temp2.push((igs.stats.goldEarned / 1000).toFixed(1) + "k");

                        if(igs.teamId == winner)
                            {temp2.push("win");}
                        else
                            {temp2.push("loss");}

                        temp2.push(mix[1]);
                        temp2.push(acid);
                        temp.push(temp2);

                        if(acid[1] == this.info.accountId){
                            if(igs.teamId == winner){
                                this.countWin++;
                            }
                            temp2.push(player.gameMode);
                            let second = Number((timetaken % 60).toFixed(2));
                            let total = (Math.floor(timetaken / 60) + (second / 100)).toFixed(2);
                            total = total.replace(/\./g, ':');
                            let d = new Date(gameCreated);
                            temp2.push(total);
                            temp2.push((d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear()));
                            me = temp2;
                        }
                    });

                    //add info to initialhis for list of history
                    this.initialhis.push(me);
                    let gameid: string[] = []
                    gameid.push((player.gameId).toString())
                    temp.push(gameid);
                    this.memberimages.push(temp);
                }
                });
                this.winRate = this.countWin + "W/" + Math.abs(this.countWin-this.initialhis.length) + "L";
            });
        });

我使用该功能是因为它不允许我在第一次搜索后多次搜索。

请给我一个解决方案。谢谢

0 个答案:

没有答案