Rectangle 27 248

(EDIT: I've added an updated solution below this explanation)

Mark Rajcok is the man... and his answer is a valid answer, but it has had a defect (sorry Mark)...

JavaScript loves events after all. Events are inherently loosely coupled, and even better, you avoid adding another $watch to your $digest.

<input type="text" focus-on="newItemAdded" />

and then anywhere in your app...

$scope.addNewItem = function () {
    /* stuff here to add a new item... */

    $scope.$broadcast('newItemAdded');
};

This is awesome because you can do all sorts of things with something like this. For one, you could tie into events that already exist. For another thing you start doing something smart by having different parts of your app publish events that other parts of your app can subscribe to.

Anyhow, this type of thing screams "event driven" to me. I think as Angular developers we try really hard to hammer $scope shaped pegs into event shape holes.

Is it the best solution? I dunno. It's a solution.

After @ShimonRachlenko's comment below, I've changed my method of doing this slightly. Now I use a combination of a service and a directive that handles an event "behind the scenes":

Other than that, it's the same principal outlined above.

<input type="text" focus-on="focusMe"/>
app.controller('MyCtrl', function($scope, focus) {
    focus('focusMe');
});
app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on('focusOn', function(e, name) {
        if(name === attr.focusOn) {
          elem[0].focus();
        }
      });
   };
});

app.factory('focus', function ($rootScope, $timeout) {
  return function(name) {
    $timeout(function (){
      $rootScope.$broadcast('focusOn', name);
    });
  }
});

You need to wrap the call to $broadcast with $timeout if you want this to work on entering the controller. Otherwise nice solution.

Yes, and that's enough for the directive to initialize. Overwise the event is broadcasted before the directive starts to listen to it.. Again, this is only needed when you want to trigger your directive when you enter the page.

Thanks for this! I've implemented your solution as an angular module here: github.com/goodeggs/ng-focus-on

This is, by far, the most elegant, "angular way" solution. Even though I mostly just copied the code when I first ran into this problem, I'm glad you made a module for it! I honestly think it might be worth attempting to get it into the core angular.

angularjs - How to set focus on input field? - Stack Overflow

angularjs angularjs-directive
Rectangle 27 248

(EDIT: I've added an updated solution below this explanation)

Mark Rajcok is the man... and his answer is a valid answer, but it has had a defect (sorry Mark)...

JavaScript loves events after all. Events are inherently loosely coupled, and even better, you avoid adding another $watch to your $digest.

<input type="text" focus-on="newItemAdded" />

and then anywhere in your app...

$scope.addNewItem = function () {
    /* stuff here to add a new item... */

    $scope.$broadcast('newItemAdded');
};

This is awesome because you can do all sorts of things with something like this. For one, you could tie into events that already exist. For another thing you start doing something smart by having different parts of your app publish events that other parts of your app can subscribe to.

Anyhow, this type of thing screams "event driven" to me. I think as Angular developers we try really hard to hammer $scope shaped pegs into event shape holes.

Is it the best solution? I dunno. It's a solution.

After @ShimonRachlenko's comment below, I've changed my method of doing this slightly. Now I use a combination of a service and a directive that handles an event "behind the scenes":

Other than that, it's the same principal outlined above.

<input type="text" focus-on="focusMe"/>
app.controller('MyCtrl', function($scope, focus) {
    focus('focusMe');
});
app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on('focusOn', function(e, name) {
        if(name === attr.focusOn) {
          elem[0].focus();
        }
      });
   };
});

app.factory('focus', function ($rootScope, $timeout) {
  return function(name) {
    $timeout(function (){
      $rootScope.$broadcast('focusOn', name);
    });
  }
});

You need to wrap the call to $broadcast with $timeout if you want this to work on entering the controller. Otherwise nice solution.

@ShimonRachlenko - Thanks. But I'm not sure what you mean by the $timeout. If I wanted to broadcast when the controller constructor was being processed, I'd just broadcast right then. A timeout wouldn't do anything but defer the broadcast to a later execution in the event loop.

Yes, and that's enough for the directive to initialize. Overwise the event is broadcasted before the directive starts to listen to it.. Again, this is only needed when you want to trigger your directive when you enter the page.

Thanks for this! I've implemented your solution as an angular module here: github.com/goodeggs/ng-focus-on

This is, by far, the most elegant, "angular way" solution. Even though I mostly just copied the code when I first ran into this problem, I'm glad you made a module for it! I honestly think it might be worth attempting to get it into the core angular.

angularjs - How to set focus on input field? - Stack Overflow

angularjs angularjs-directive
Rectangle 27 247

(EDIT: I've added an updated solution below this explanation)

Mark Rajcok is the man... and his answer is a valid answer, but it has had a defect (sorry Mark)...

JavaScript loves events after all. Events are inherently loosely coupled, and even better, you avoid adding another $watch to your $digest.

<input type="text" focus-on="newItemAdded" />

and then anywhere in your app...

$scope.addNewItem = function () {
    /* stuff here to add a new item... */

    $scope.$broadcast('newItemAdded');
};

This is awesome because you can do all sorts of things with something like this. For one, you could tie into events that already exist. For another thing you start doing something smart by having different parts of your app publish events that other parts of your app can subscribe to.

Anyhow, this type of thing screams "event driven" to me. I think as Angular developers we try really hard to hammer $scope shaped pegs into event shape holes.

Is it the best solution? I dunno. It's a solution.

After @ShimonRachlenko's comment below, I've changed my method of doing this slightly. Now I use a combination of a service and a directive that handles an event "behind the scenes":

Other than that, it's the same principal outlined above.

<input type="text" focus-on="focusMe"/>
app.controller('MyCtrl', function($scope, focus) {
    focus('focusMe');
});
app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on('focusOn', function(e, name) {
        if(name === attr.focusOn) {
          elem[0].focus();
        }
      });
   };
});

app.factory('focus', function ($rootScope, $timeout) {
  return function(name) {
    $timeout(function (){
      $rootScope.$broadcast('focusOn', name);
    });
  }
});

You need to wrap the call to $broadcast with $timeout if you want this to work on entering the controller. Otherwise nice solution.

Yes, and that's enough for the directive to initialize. Overwise the event is broadcasted before the directive starts to listen to it.. Again, this is only needed when you want to trigger your directive when you enter the page.

Thanks for this! I've implemented your solution as an angular module here: github.com/goodeggs/ng-focus-on

This is, by far, the most elegant, "angular way" solution. Even though I mostly just copied the code when I first ran into this problem, I'm glad you made a module for it! I honestly think it might be worth attempting to get it into the core angular.

angularjs - How to set focus on input field? - Stack Overflow

angularjs angularjs-directive
Rectangle 27 3

The code snippet by Matt Handy is the correct solution, but the explanation of the cause is incorrect.

You've omitted the execute attribute of the <f:ajax> in the commandbutton. It will then default to @this which means that only the name=value pair of the button itself is been sent to the server side (and thus only the associated action will be invoked; the input values won't be updated). Since you want to submit the entire form instead, you need to explicitly set execute to @form.

<h:commandButton value="Send" id="sendButton" action="#{chat.send}">
  <f:ajax execute="@form" render=":chatLogId :chatId" />
</h:commandButton>

That it works during change of the input field is because you've put execute="@form" in the input field instead. The <f:ajax> inside input fields will by default be executed when you change the value. But in this particular case you don't need it at all. So get rid of it:

<h:inputText id="chatInput" value="#{chat.msgTo}" autocomplete="off" />

Thanks for the replies Matt and BalusC. I tried to just have f:ajax in the commandButton, and also just the inputText, but the behavior is still the same. The first time I changed the input field and either pressed enter, or clicked on the button, the input field was reset to the default 'Start Typing...'. The second time I changed the input field, everything worked. It's like my input is direct somewhere else the first time. Thanks. Binh

Were the changes republished to the server?

ajax - ajax jsf jsf-2

Rectangle 27 46

The answer that @lzap gave is a good solution. However, I would like to add that you should add . to the class path, so that your current directory is not left out, resulting in your own classes to be left out. This has happened to me on some platforms. So an updated version for JUnit 4.x would be:

java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name]

@panny it's a semicolon on Windows. On n *nix environment (at least OSX and all the Linux distros I've used) you use a colon.

@rand_acs does the test class name need to be the fully classified class name ?

@Goaler444 Yes, I always use the full name, with all the namespaces specified.

unit testing - How to run JUnit test cases from the command line - Sta...

unit-testing command-line junit
Rectangle 27 143

UPDATE: Since a lot of time has passed after this answer and new methods/APIs have been added, please check the updated answers below for Swift etc; Since I've not used them myself, I can't vouch for them. Original answer: I found the following solution working for me:

-(uint64_t)getFreeDiskspace {
    uint64_t totalSpace = 0;
    uint64_t totalFreeSpace = 0;
    NSError *error = nil;  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];  

    if (dictionary) {  
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];  
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
        totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
        NSLog(@"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
    } else {  
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
    }  

    return totalFreeSpace;
}

It returns me exactly the size that iTunes displays when device is connected to machine.

Converting to a float may give inaccurate results above around 2GB. If you need to deal with really large file sizes, use a double or long double instead.

The code snippet has been edited to reflect suggestions from @David H as shown below.

[error code] should not use %@ when format using NSLog.

+200 MB is not a problem. In the Settings I have "0 bytes" available space. And when I enter and use my app, this method reports about 150mb free space. Then I fill up this remaining space and only then the app crashes. So I would say that this method gives you more correct information than what you see in Settings.

Why is no one using NSUInteger instead of stuff like uint64_t ? We're writing Obj-C, not C++ or C. NSUInteger will give you an unsigned 64 bit integer now, but if things happen to change I imagine that Apple will update that Macro (let's say 128 bits at some point, becomes real)

ios - How to detect total available/free disk space on the iPhone/iPad...

iphone ios ipad nsfilemanager diskspace
Rectangle 27 143

UPDATE: Since a lot of time has passed after this answer and new methods/APIs have been added, please check the updated answers below for Swift etc; Since I've not used them myself, I can't vouch for them. Original answer: I found the following solution working for me:

-(uint64_t)getFreeDiskspace {
    uint64_t totalSpace = 0;
    uint64_t totalFreeSpace = 0;
    NSError *error = nil;  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];  

    if (dictionary) {  
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];  
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
        totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
        NSLog(@"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
    } else {  
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
    }  

    return totalFreeSpace;
}

It returns me exactly the size that iTunes displays when device is connected to machine.

Converting to a float may give inaccurate results above around 2GB. If you need to deal with really large file sizes, use a double or long double instead.

The code snippet has been edited to reflect suggestions from @David H as shown below.

[error code] should not use %@ when format using NSLog.

+200 MB is not a problem. In the Settings I have "0 bytes" available space. And when I enter and use my app, this method reports about 150mb free space. Then I fill up this remaining space and only then the app crashes. So I would say that this method gives you more correct information than what you see in Settings.

Why is no one using NSUInteger instead of stuff like uint64_t ? We're writing Obj-C, not C++ or C. NSUInteger will give you an unsigned 64 bit integer now, but if things happen to change I imagine that Apple will update that Macro (let's say 128 bits at some point, becomes real)

ios - How to detect total available/free disk space on the iPhone/iPad...

iphone ios ipad nsfilemanager diskspace
Rectangle 27 142

UPDATE: Since a lot of time has passed after this answer and new methods/APIs have been added, please check the updated answers below for Swift etc; Since I've not used them myself, I can't vouch for them. Original answer: I found the following solution working for me:

-(uint64_t)getFreeDiskspace {
    uint64_t totalSpace = 0;
    uint64_t totalFreeSpace = 0;
    NSError *error = nil;  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];  

    if (dictionary) {  
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];  
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
        totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
        NSLog(@"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
    } else {  
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
    }  

    return totalFreeSpace;
}

It returns me exactly the size that iTunes displays when device is connected to machine.

Converting to a float may give inaccurate results above around 2GB. If you need to deal with really large file sizes, use a double or long double instead.

The code snippet has been edited to reflect suggestions from @David H as shown below.

[error code] should not use %@ when format using NSLog.

+200 MB is not a problem. In the Settings I have "0 bytes" available space. And when I enter and use my app, this method reports about 150mb free space. Then I fill up this remaining space and only then the app crashes. So I would say that this method gives you more correct information than what you see in Settings.

Why is no one using NSUInteger instead of stuff like uint64_t ? We're writing Obj-C, not C++ or C. NSUInteger will give you an unsigned 64 bit integer now, but if things happen to change I imagine that Apple will update that Macro (let's say 128 bits at some point, becomes real)

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

ios - How to detect total available/free disk space on the iPhone/iPad...

iphone ios ipad nsfilemanager diskspace
Rectangle 27 3

I was not aware that the datepicker had lost the "Clear" button! I started looking at this and tried to make a solution that did not rely on adding another element or assuming that users will know that pressing Esc closes the widget. Although you could just give the users an explanation of that functionality, which might solve your problem ;-)

So I made a demo in which I have replaced the "Close" button text with "Clear". I have added one extra jQuery mouseup delegated event on my new "Clear" button which will clear the input before the standard datepicker events fire.

So either clicking "Clear" or using backspace to delete a date and then Esc to close the datepicker will revert the second input back to the default datepicker state.

Note that for this demo every time a date is selected in the first input the range on the second is set. This may not be your desired functionality.

Edit: Updated demo Ahhh yes, that does complicate things somewhat! I've re-worked the solution to be a lot more generic and I think I have it working. The new demo creates all the datepicker objects in one go. There were a couple of tricky parts, namely the generic clearing of the "next" <input> elements and correctly determining which <input> to clear when the "clear" button is pressed. I was not aware that there is only one datepicker. So it's a bit of a hack as it just sets a jQuery .data() property on the input that has the datepicker visible and then use that to clear the correct one later. Note that in this demo it still resets all subsequent inputs if one is cleared, i.e. "clearing" the first clears 2 and 3 but clearing the second only clears the 3rd.

Unfortunately this doesn't work 100% . The problem is that there is only 1 div for all datepickers on the page (an optimization I suppose). So using $('#firstDate').datepicker('widget').delegate() and $('#secondDate').datepicker('widget').delegate() registers 2 listeners on the one and only "clear" button. As a result clicking on any "clear" button clears all datepicker input fields (but only triggers the correct onClose). Will have to dig through the jQueryUI code to solve this.

jquery - Reset date range constraints - Stack Overflow

jquery jquery-ui datepicker
Rectangle 27 3

I was not aware that the datepicker had lost the "Clear" button! I started looking at this and tried to make a solution that did not rely on adding another element or assuming that users will know that pressing Esc closes the widget. Although you could just give the users an explanation of that functionality, which might solve your problem ;-)

So I made a demo in which I have replaced the "Close" button text with "Clear". I have added one extra jQuery mouseup delegated event on my new "Clear" button which will clear the input before the standard datepicker events fire.

So either clicking "Clear" or using backspace to delete a date and then Esc to close the datepicker will revert the second input back to the default datepicker state.

Note that for this demo every time a date is selected in the first input the range on the second is set. This may not be your desired functionality.

Edit: Updated demo Ahhh yes, that does complicate things somewhat! I've re-worked the solution to be a lot more generic and I think I have it working. The new demo creates all the datepicker objects in one go. There were a couple of tricky parts, namely the generic clearing of the "next" <input> elements and correctly determining which <input> to clear when the "clear" button is pressed. I was not aware that there is only one datepicker. So it's a bit of a hack as it just sets a jQuery .data() property on the input that has the datepicker visible and then use that to clear the correct one later. Note that in this demo it still resets all subsequent inputs if one is cleared, i.e. "clearing" the first clears 2 and 3 but clearing the second only clears the 3rd.

Unfortunately this doesn't work 100% . The problem is that there is only 1 div for all datepickers on the page (an optimization I suppose). So using $('#firstDate').datepicker('widget').delegate() and $('#secondDate').datepicker('widget').delegate() registers 2 listeners on the one and only "clear" button. As a result clicking on any "clear" button clears all datepicker input fields (but only triggers the correct onClose). Will have to dig through the jQueryUI code to solve this.

jquery - Reset date range constraints - Stack Overflow

jquery jquery-ui datepicker
Rectangle 27 3

I finally found a solution that meets all my requirements by adding just one line of CSS to .box > p: -webkit-mask-image (accepted answer by Adrian van Vliet). I've updated my codepen to show this solution: http://codepen.io/thdoan/pen/wKZBrN

Even though this is considered "non-standard" CSS, it's no big deal for my case since if a browser doesn't support it then the content will degrade gracefully to white text simply not having a gradient fade. In the meantime, I am experimenting with another solution that is more cross-browserish using SVG: Applying SVG effects to HTML content. I will update this answer with a codepen using an SVG mask if I ever get it to work.

The full cross-browser solution is laid out in the nice tutorial, CSS Masks How To Use Masking In CSS Now by Christian Schaefer.

I got a 404 while trying to go to your "CSS Masks" link. Could you update it?

opacity - How to fade out text on top of semi-transparent div using CS...

css opacity fadeout
Rectangle 27 3

I fixed the issue by adding the JAXB jars to my classpath on the client side. I don't know why this solved the problem but I would guess it's because the @XmlRootElement and other JAXB annotations in my POJOs were simply ignored at runtime because the jars were not present. This resulted in Jersey not detecting the annotations and thus thinking it had no way of translating between the xml and POJO on the client side. I discovered the solution when I tried the alternative way that avoids the need for annotations, where you wrap the root POJO in a JAXBElement. I updated the web service class to produce a JAXBElement and updated the client to expect the same. Then I got a NoClassDefFoundError that was more indicative of the missing jars, since I was referencing JAXBElement directly. I guess I got lucky.

xml - Jersey Client message body reader for Java type not found - Stac...

xml rest jaxb jersey
Rectangle 27 0

Unfortunately, we didn't find a great solution for this. It seems like the only way to mix .net events and JQuery AJAX effectively is if the elements you are updating are either 100% JQuery or 100% .net events. For example, if you are dynamically adding some sort of object like a picture with a set of links (e.g. edit and delete) then the links should either both use manual AJAX (i.e. JQuery calling a WebMethod) and then update the DOM using JQuery; OR both links should call a .net event in an update panel. If you try to make one link JQuery and the other link a .net event then you'll get issues where .net doesn't know that the DOM has been updated by JQuery and your events could get hosed up. It would be very difficult to predict what are the appropriate IDs to set in your DOM so that .NET doesn't get confused (if you are using JQuery). When .NET 4.0 comes it this should get a lot easier since you'll have the option to manually specify the control IDs instead of .NET producing it's own crazy IDs.

.net - Dynamically Added Client Script/HTML Calling Server-Side Event ...

.net asp.net javascript jquery ajax
Rectangle 27 0

I'll add my solution here as I couldn't find it mentioned here yet. I have a dynamic button whose image depends on the state of one control. The most simple solution for me was to set the image to nil if the control was not present. The image was updated each time the control updated and thus, this was optimal for me. Just to be sure I also set the enabled to NO.

Setting the width to a minimal value did not work on iOS 7.

ios - How do I show/hide a UIBarButtonItem? - Stack Overflow

ios uibarbuttonitem uitoolbar
Rectangle 27 0

I just ran into this problem myself in Opera so borrowed Sanesh Fernando's solution which worked around the hidden fields not being reinstated (Thanks Sanesh). However what caused a problem for me was that Javascript fires before the form fields are updated so if you check values with javascript as I was doing then I had to add a setTimeout to ensure Opera updated before I checked the values.

Cookies are as stated another way but what with the ridiculous EU directive on requiring cookie usage agreement from the visitor it's not a solution for me.

Chrome doesn't cache hidden form field values for use in browser histo...

google-chrome browser-history hidden-fields back-button
Rectangle 27 0

I just ran into this problem myself in Opera so borrowed Sanesh Fernando's solution which worked around the hidden fields not being reinstated (Thanks Sanesh). However what caused a problem for me was that Javascript fires before the form fields are updated so if you check values with javascript as I was doing then I had to add a setTimeout to ensure Opera updated before I checked the values.

Cookies are as stated another way but what with the ridiculous EU directive on requiring cookie usage agreement from the visitor it's not a solution for me.

Chrome doesn't cache hidden form field values for use in browser histo...

google-chrome browser-history hidden-fields back-button
Rectangle 27 0

I would personally tend towards the solution Flimzy provided here for it's simplicity. But just to provide alternative options, you could add a flag for each property to indicate whether or not it's been updated.

type Test struct {
    FieldInt int
    FieldBool bool
    FieldString string

    intUpdated bool
    boolUpdated bool
    stringUpdate bool
    // lets not export these though since it's for managing state
    // internally and consumers of this object shouldn't modify these values
}

To me this is rather a strange thing to see in Go code, however it would be very common place in JS UI apps (almost all modern apps have 'stores' which monitor the state of the UI and typically have flags to indicate whether a value in the UI has changed from what's in the store or not). For back end systems, you usually see even MORE overhead to go with this, for example it would be very common to have fields to store the last time of update and the name of the user who updated it. In fact, that is probably the norm within the data stores for back end services.

go - How to distinguish between default value and inputed/changed in G...

go
Rectangle 27 0

The solution I came up with was to use a dynamic [formGroupName] which references an array which is updated each time a new group is added

[formGroupName]="myGroupName[i]"
import { Component, OnInit } from '@angular/core';
import { Customer } from './customer.interface';
import { FormControl, FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';


@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.component.html',
})
export class AppComponent implements OnInit {
    public myForm: FormGroup;

      myGroupName = ['test'];


    constructor(private _fb: FormBuilder) { 
    }

    ngOnInit() {
        this.myForm = this._fb.group({

            myArray: this._fb.array([
                this._fb.group({  
                   test: this._fb.group({
                        name: ['test'],
                            title: [''],
                          link: [''],
                            cta: [''],

                    })
                }), 

            ])
        });
    }


 initArray(nameObj:any) {
      return  this._fb.group({  
                [nameObj]: this._fb.group({
                        name: [nameObj],
                          title: [''],
                        link: [''],
                          cta: [''],

                    })
                })
    }

 addArray(newName:string) {
        const control = <FormArray>this.myForm.controls['myArray'];
        this.myGroupName.push(newName);
        control.push(this.initArray(newName));
            document.getElementById('newName').value='';
    }



  removeDataKey(i: number) {
       const control = <FormArray>this.myForm.controls['myArray'];
       control.removeAt(i);
       this.myGroupName.splice(i,1);
    }

}
<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm)">

      <div formArrayName="myArray"> 

         <div *ngFor="let myGroup of myForm.controls.myArray.controls; let i=index" class="panel panel-default">

           <div [formGroupName]="i" class="panel-body"> 
              <span *ngIf="myForm.controls.myArray.controls.length > 1" 
                    (click)="removeDataKey(i)" class="glyphicon glyphicon-remove pull-right">
                </span>
             <h5 >Group {{i + 1 }}</h5>
            <h3>  {{myGroupName[i] }}</h3>

              <!--[formGroupName]="myGroupName[i]"-->
              <div [formGroupName]="myGroupName[i]" class="panel-body"> 


              <div class="form-group">
              <label>Title</label>
              <input type="text" class="form-control" formControlName="title" >
              </div>

              <div class="form-group">
              <label>Link</label>
              <input type="text" class="form-control" formControlName="link" >
              </div> 

              <div class="form-group">
              <label>Cta</label>
              <input type="text" class="form-control" formControlName="cta" >
              </div>


              </div>
              <!--[formGroupName]="myGroupName[i]"-->

        </div>
         <!--[formGroupName]="i" -->
      </div>

    </div>
     <!-- myArray array-->

        <div class="margin-20">

        <input #newName
      (keyup.enter)="addName(newName.value)"
       type="text" style="width:30%" id="newName">


        <a (click)="addArray(newName.value)" style="cursor: default" class="btn">Add Group  +</a>



        </div>
</form>

The dupe of this question is also answered here with related plunks

javascript - angular2 using input to dynamically add to form model - S...

javascript angular